Try-With-Resources: Automatic Resource Management
What you'll learn: How to use Java's try-with-resources syntax to automatically close streams and eliminate risky manual cleanup code.
The Problem Solved
You've seen that closing streams manually requires a finally block, which leads to verbose, error-prone code. If an exception occurs during close(), it can suppress the original exception you were trying to handle—a debugging nightmare. Java 7 introduced try-with-resources to solve this elegantly.
How Try-With-Resources Works
The syntax looks like this:
try (FileInputStream fis = new FileInputStream("data.bin")) {
// Use the stream
int data = fis.read();
// ...
} // Stream automatically closed here
Notice the resource declaration inside the parentheses after try. When the block exits—whether normally or via exception—Java automatically calls close() on the resource. No manual cleanup needed.
Multiple Resources
You can declare multiple resources separated by semicolons:
try (FileInputStream in = new FileInputStream("input.txt");
FileOutputStream out = new FileOutputStream("output.txt")) {
// Copy operation
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} // Both streams closed automatically in reverse order
Why This Matters
Think of try-with-resources like a restaurant that automatically clears your table when you leave—you don't have to remember to return dishes. The compiler guarantees cleanup happens, and if exceptions occur during both your code and during close(), Java properly records both (the close exception becomes "suppressed" but isn't lost).
Any class implementing AutoCloseable works with this syntax—including all streams.
Key Takeaway: Use try-with-resources for all I/O operations to guarantee automatic stream closure without manual finally blocks, eliminating resource leaks and exception-handling bugs.