Reading & writing text with try-with-resources
Reliable file reading and writing — and why you must always close streams.
Try-with-resources — the only safe pattern
A stream holds an OS file descriptor. If you forget to close it, the resource leaks — and eventually the JVM or OS will run out of file handles. Try-with-resources (TWR) guarantees close() is called even if an exception is thrown:
try (BufferedReader br = new BufferedReader(new FileReader("notes.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} // br.close() called automatically here — even if readLine() threw
readLine() returns null at end of file — that is the loop-termination condition, not an exception.
Writing with PrintWriter:
try (PrintWriter pw = new PrintWriter(new BufferedWriter(
new FileWriter("output.txt", StandardCharsets.UTF_8)))) {
pw.println("First line");
pw.printf("Count: %d%n", 42);
}
Multiple resources in one TWR are closed in reverse declaration order:
try (InputStream in = new FileInputStream("a.bin");
OutputStream out = new FileOutputStream("b.bin")) {
// closed: out first, then in
}
The resource variable must implement AutoCloseable. If both the body and close() throw, the close exception is suppressed (added to the primary exception via addSuppressed).