HOME HTML EDITOR C JAVA PHP

Java File Handling: Permanent Data Storage

File Handling allows a Java program to read data from and write data to files. In Java, files are treated as Streams—a continuous flow of data. To handle these streams, Java provides the File class from the java.io package. This module covers the core CRUD operations (Create, Read, Update, Delete) for files.

1. The File Class

The File class is an abstract representation of file and directory pathnames. It doesn't actually "open" the file; it provides methods to check if a file exists, get its size, or delete it.

Essential File Methods:

2. Creating a File

To create a file, we use the createNewFile() method. This method returns a boolean: true if the file was created successfully, and false if it already exists.

import java.io.File;
import java.io.IOException;

File myFile = new File("filename.txt");
if (myFile.createNewFile()) {
  System.out.println("File created: " + myFile.getName());
} else {
  System.out.println("File already exists.");
}

3. Writing to a File (FileWriter & BufferedWriter)

To write text to a file, we use the FileWriter class. However, for better performance (especially with large data), we wrap it in a BufferedWriter, which buffers the characters so the system doesn't have to write to the disk for every single character.

try (FileWriter writer = new FileWriter("filename.txt")) {
  writer.write("Java File Handling is powerful!");
  System.out.println("Successfully wrote to the file.");
} catch (IOException e) { ... }

Tip: By default, FileWriter overwrites the file. To append data instead, use new FileWriter("filename.txt", true).

4. Reading a File (Scanner vs. BufferedReader)

There are two popular ways to read files in Java:

Scanner Class

Easy to use. Great for reading data word-by-word or line-by-line using nextLine(). Ideal for small files.

BufferedReader

Extremely fast for large files. It reads large chunks of data into memory at once, reducing disk access.

// Reading using Scanner
try (Scanner reader = new Scanner(myFile)) {
  while (reader.hasNextLine()) {
    String data = reader.nextLine();
    System.out.println(data);
  }
}

5. Deleting a File

To delete a file, simply call the delete() method. Note that this cannot be undone!

if (myFile.delete()) {
  System.out.println("Deleted the file: " + myFile.getName());
} else {
  System.out.println("Failed to delete the file.");
}

6. Modern Java: java.nio (Files Class)

In Java 7+, the NIO (New Input/Output) package was introduced. The java.nio.file.Files class provides static methods that make file operations even simpler.

7. Mastery Code Example: Simple Logger

A complete program that creates a log file and appends a timestamped message.

import java.io.*;
import java.time.LocalDateTime;

public class FileLogger {
  public static void main(String[] args) {
    try (BufferedWriter bw = new BufferedWriter(new FileWriter("app.log", true))) {
      bw.write("Log Entry: " + LocalDateTime.now());
      bw.newLine();
      System.out.println("Log updated.");
    } catch (IOException e) {
      System.out.println("Error occurred.");
    }
  }
}

8. Interview Preparation: Q&A Mastery

Q: What is the difference between a Stream and a File?
A: A File is a physical resource on the disk. A Stream is the "pipe" used to transfer data into or out of that file.

Q: Why should we use try-with-resources with File I/O?
A: File streams occupy system resources (file handles). If not closed, they can lead to memory leaks or file locking. Try-with-resources ensures they are closed automatically.

Q: What is Serialization?
A: It is the process of converting a Java Object into a byte stream so it can be saved to a file or sent over a network. We use ObjectOutputStream for this.

Final Verdict

File handling is the gateway to creating real-world software. By understanding the File class for management, Streams for data flow, and NIO for modern efficiency, you can ensure your application's data survives long after the power is turned off.

Next: Multi-Threading in Java →