What is File Handling :
- File handling refers to the process of creating, reading, writing, updating, and deleting files stored on disk.
- Java provides rich APIs in java.io and java.nio.file to work with files seamlessly across all operating systems.
- It helps programs to store data permanently instead of only in memory.
The java.io Package :
- The java.io package is the traditional approach to file handling in Java. The central class is File — it represents a file or directory path on your system but doesn't actually read or write data by itself.
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
Creating & Checking Files :
Use File.createNewFile() to create a new empty file. It returns true if the file was created, false if it already exists.
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
File file = new File("data.txt");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- Writing to a File
Use FileWriter to write text content to a file. By default it overwrites the existing content. Wrap it in a BufferedWriter for efficiency.
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("data.txt")) {
writer.write("Hello, Java File Handling!\n");
writer.write("Line 2: Learning I/O in Java.");
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Reading from a File :
- Combine FileReader with BufferedReader to read files line by line. This is memory-efficient even for large files.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
try (BufferedReader reader =
new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.java.nio.file package :
- Newer and better (introduced later)
- Faster + more powerful + cleaner
Works with:
- Path
- Files Example:
Path path = Paths.get("test.txt");
Files.readAllLines(path);
- Since Java 7, the java.nio.file package (NIO.2) offers a cleaner, more powerful API via Files and Paths. It's the recommended approach for new projects.
import java.nio.file.*;
import java.io.IOException;
import java.util.List;
public class NioExample {
public static void main(String[] args) throws IOException {
Path path = Paths.get("notes.txt");
// Write all lines at once
Files.writeString(path, "NIO.2 makes file I/O easy!\n");
// Read all lines into a List
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);
// Check if file exists
boolean exists = Files.exists(path);
System.out.println("Exists: " + exists);
// Delete using NIO
Files.deleteIfExists(path);
}
}
Advantages of File Handling :
Persistent data storage — data survives program termination, unlike in-memory variables
Platform independence — write once, runs the same on Windows, Linux, and macOS
Data sharing — files let completely separate programs exchange data easily (CSV, JSON, XML)
Handles large data efficiently — buffered I/O processes huge files without memory issues
Logging & auditing — write activity logs and audit trails to files for debugging and compliance
Backup & recovery — export and restore app state from files after crashes
Configuration management — change settings in .properties or .json files without recompiling.
Multiple file formats — same Java I/O concepts work for text, binary, images, PDFs, and more.
Top comments (0)