All 15 I/O & NIO questions
More in I/O & NIO
Advertisement
Java › I/O & NIO

How would you use try-with-resources combined with multiple chained I/O wrapper classes (like FileInputStream wrapped in BufferedInputStream wrapped in GZIPInputStream) to correctly read a compressed file while ensuring all layers are properly closed?

Intermediate

Answer

Multiple resources can be declared together in a single try-with-resources statement (separated by semicolons), each closed automatically in REVERSE declaration order once the try block exits, correctly unwinding a chain of wrapped streams in the proper sequence (closing the outermost wrapper first, which is generally the correct order for chained streams, though many wrapper implementations delegate their close() call down through the chain automatically, meaning closing just the outermost wrapper is often actually sufficient by itself).
try (FileInputStream fis = new FileInputStream("data.txt.gz");
     GZIPInputStream gzis = new GZIPInputStream(fis);
     BufferedReader reader = new BufferedReader(new InputStreamReader(gzis, StandardCharsets.UTF_8))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
}  // all three resources closed automatically, in reverse order: reader, then gzis, then fis
Real-world example A log-processing utility reading gzip-compressed log files chains FileInputStream, GZIPInputStream, and BufferedReader together within a single try-with-resources statement, guaranteeing all three layers are properly closed even if an exception occurs partway through reading, without needing nested try-finally blocks for each individual wrapper layer.

Common follow-ups: Is it actually necessary to declare all three resources explicitly, given closing just the outermost reader would typically cascade through to close the underlying wrapped streams as well?;What happens if one of the resources fails to construct successfully partway through the declaration list -- are the already-constructed ones still closed properly?