☕ Java
File Handling in Java
Most real applications read from and write to files — config files, logs, exports, uploads. Java gives you classic I/O streams for fine-grained control and the modern java.nio.file API for clean, readable code. Know both.
Writing to a File
The try-with-resources pattern (try with the resource declared in parentheses) automatically closes the file when you're done — even if an exception occurs. Always use this over manually calling .close().
Java
import java.io.*;
// try-with-resources — file is automatically closed after the block
try (FileWriter fw = new FileWriter("log.txt", true); // 'true' = append mode
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write("Application started at: " + new java.util.Date());
bw.newLine();
bw.write("User logged in: alice@example.com");
bw.newLine();
} catch (IOException e) {
System.err.println("Failed to write log: " + e.getMessage());
}
// BufferedWriter is closed automatically — no need for finally blockReading from a File
Java
import java.io.*;
// BufferedReader wraps FileReader for line-by-line reading (much more efficient)
try (FileReader fr = new FileReader("config.txt");
BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) { // readLine returns null at end of file
System.out.println(line);
// Parse config: String[] parts = line.split("=");
}
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}java.nio.file — The Modern Approach (Recommended)
The java.nio.file package (introduced in Java 7, enhanced in Java 8+) is cleaner, more powerful, and handles large files better. For new code, prefer this over the classic java.io approach.
Java
import java.nio.file.*;
import java.util.List;
// Write a file (overwrites by default)
Files.writeString(Path.of("output.txt"), "Hello from NIO!
Second line");
// Append to a file
Files.writeString(Path.of("output.txt"), "
Appended line",
StandardOpenOption.APPEND);
// Read all lines into a List
List<String> lines = Files.readAllLines(Path.of("output.txt"));
lines.forEach(System.out::println);
// Read entire file as one String
String content = Files.readString(Path.of("output.txt"));
// File existence and metadata
Path p = Path.of("output.txt");
System.out.println(Files.exists(p)); // true
System.out.println(Files.size(p)); // file size in bytes
System.out.println(Files.isReadable(p)); // true
// Delete
Files.deleteIfExists(p); // safer than delete() — won't throw if file doesn't exist