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.
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.
exists(): Returns true if the file is present.getName(): Returns the name of the file.getAbsolutePath(): Returns the full path (e.g., C:\Users\Admin\data.txt).length(): Returns the size of the file in bytes.delete(): Removes the file from the disk.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.
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).
There are two popular ways to read files in Java:
Easy to use. Great for reading data word-by-word or line-by-line using nextLine(). Ideal for small files.
Extremely fast for large files. It reads large chunks of data into memory at once, reducing disk access.
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.");
}
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.
Files.readAllLines(path): Reads the whole file into a List of Strings in one line of code.Files.write(path, bytes): Writes a byte array directly to a file.Files.copy(source, target): Copies a file from one location to another.A complete program that creates a log file and appends a timestamped message.
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.
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 →