Multiple Resources in Try-With-Resources
What You'll Learn
You'll discover how to manage multiple resources simultaneously using try-with-resources, ensuring they all close automatically in the correct order.
Managing Multiple Resources at Once
In the previous lesson, you learned the basic try-with-resources syntax for a single resource. But what happens when you need to work with multiple resources—like reading from one file while writing to another?
Java lets you declare multiple resources in a single try-with-resources statement by separating them with semicolons. Each resource must implement AutoCloseable, and Java guarantees that all resources will be closed automatically.
The Syntax
try (Resource1 r1 = new Resource1();
Resource2 r2 = new Resource2();
Resource3 r3 = new Resource3()) {
// Use r1, r2, and r3
}
Notice the semicolons separating each resource declaration. You can declare as many as you need.
The Critical Detail: Reverse Order Closing
Here's what makes this powerful: resources are closed in the reverse order of their declaration. If you declare r1, then r2, then r3, Java closes them as r3, r2, r1.
Think of it like stacking dishes: the last dish you put on top is the first one you take off. This reverse order matters when resources depend on each other—you want to close the dependent resource before closing what it depends on.
A Practical Example
try (FileInputStream input = new FileInputStream("source.txt");
FileOutputStream output = new FileOutputStream("dest.txt")) {
// Read from input, write to output
// Both close automatically, output first, then input
}
Even if an exception occurs while closing one resource, Java will still attempt to close the others (any suppressed exceptions are tracked).
Key Takeaway: Declare multiple resources in try-with-resources using semicolons; all close automatically in reverse declaration order, ensuring proper cleanup even when resources depend on each other.