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?
IntermediateAnswer
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 fisReal-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.