try-with-resources for File I/O in Java
File-handling classes like FileReader, FileWriter, BufferedReader, and FileInputStream all implement AutoCloseable, which makes them a natural fit for try-with-resources — declaring one in a try's parentheses guarantees it gets closed once the block ends, whether that block finished normally or an exception interrupted it partway through. This matters specifically for files because an unclosed file handle can leak an operating-system resource, and on some systems can even leave a file locked or its written content not fully flushed to disk if the program doesn't close it properly before exiting.
Multiple resources can be declared in the same try's parentheses, separated by semicolons, and Java closes them automatically in the reverse of their declaration order. The last resource opened is the first one closed, which matters when resources depend on each other, like a BufferedReader that wraps a FileReader.
File classes implement AutoCloseable
FileReader, FileWriter, BufferedReader, and similar all support try-with-resources directly.
Guaranteed closing
A resource declared in try's parentheses is closed once the block ends, exception or not.
Why it matters for files specifically
An unclosed file can leak an OS-level resource or leave written content not fully flushed to disk.
Multiple resources, one try
Separated by semicolons inside the same parentheses, all managed automatically together.
Reverse-order closing
The most recently opened resource closes first, correctly unwinding dependencies like a reader wrapped around another reader.
import java.io.FileWriter;import java.io.BufferedWriter; public class TryWithResourcesFileDemo { public static void main(String[] args) throws Exception { try (FileWriter fw = new FileWriter("log.txt"); BufferedWriter bw = new BufferedWriter(fw)) { bw.write("Log entry recorded"); } System.out.println("Both resources closed automatically"); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.