Course contentsShow
← Java
Lesson 1947 of 2,87039. File I/O: Basic Byte StreamsFree lesson

Multiple Resources in Try-With-Resources

Declaring and auto-closing multiple streams in a single try statement with proper semicolon separation.

Multiple Resources in Try-With-Resources

You'll learn how to declare and automatically close multiple streams in a single try-with-resources statement using proper semicolon separation.

The Core Idea

So far, you've seen try-with-resources manage a single stream automatically. But real-world I/O often involves multiple resources that need closing—like reading from one file while writing to another. Java's try-with-resources syntax lets you declare multiple resources in the parentheses, separated by semicolons, and they'll all be closed automatically in the correct order.

Think of it like closing multiple doors when leaving a building: you want each one shut securely, in the reverse order you opened them.

Syntax and Order

try (FileInputStream in = new FileInputStream("source.txt");
     FileOutputStream out = new FileOutputStream("dest.txt")) {
    
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
        out.write(buffer, 0, bytesRead);
    }
}
// Both streams automatically closed here

Key points:

  • Separate each resource declaration with a semicolon
  • Resources are closed in reverse order of declaration (out first, then in)
  • If closing one resource throws an exception, the others still close (with suppressed exceptions tracked)

Why Reverse Order Matters

Closing in reverse order prevents dependencies from breaking. If the FileOutputStream depends on data from the FileInputStream, you want to close the output stream first to ensure all data is flushed before closing the input.

Layering Buffers

You can even combine multiple layers:

try (FileInputStream fis = new FileInputStream("data.bin");
     BufferedInputStream bis = new BufferedInputStream(fis)) {
    // Use bis for reading
}

Key Takeaway: Try-with-resources handles multiple streams gracefully—just declare them with semicolons, and Java closes them all in reverse order, even if exceptions occur.