File Handling

Thinking

Think about how applications save game progress, logs, or user settings — all of this requires file access. File handling in Java allows programs to read from and write to files, which is fundamental for persistent data storage.

Understanding Java’s file handling mechanisms unlocks a wide range of possibilities in building data-driven and real-world applications that interact with external systems.

Description

File Handling in Java enables applications to create, read, update, and delete files. It uses classes from the java.io and java.nio.file packages to perform operations.

Common Classes Used:

  • File – Represents a file or directory.
  • FileReader, BufferedReader – For reading from files.
  • FileWriter, BufferedWriter, PrintWriter – For writing to files.
  • Scanner – Used to read content from files line by line.
  • Files – NIO.2 class for advanced file operations.
Tip:

Always close file streams using try-with-resources or manually to avoid memory leaks.

Video Resources

Examples (code)

Create and Write to a File


import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("example.txt")) {
            writer.write("Hello, File Handling in Java!");
            System.out.println("File written successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  

Read from a File


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFileExample {
    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            Scanner scanner = new Scanner(file);

            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }

            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
  

Real-World Applications

Data Storage

Storing and retrieving logs, configuration files, and data without using a database.

File Upload/Download

Processing files uploaded by users in desktop and web applications.

Code Compilers

Storing temporary files or output files during compilation or execution.

Interview Questions

Q1: What is the difference between FileWriter and BufferedWriter?

Show Answer

FileWriter writes directly to a file, while BufferedWriter uses a buffer to improve writing performance by minimizing IO operations.

Q2: How do you ensure a file is closed after operations?

Show Answer

Use the try-with-resources statement which automatically closes the file streams, or manually call close() in a finally block.

Q3: What is the use of the File class in Java?

Show Answer

The File class represents a file or directory path and provides methods to create, delete, or check file information (like existence, length, or type).