You need to close only the BufferedReader
in your scenario.
As others have pointed out, the JavaDocs are ambiguous. Using the try-with-resources block is the best approach when you want close
to be called right away, but it doesn't work if you need to keep the reader open (e.g. a class that has a method that returns a stream which uses an underlying reader--it would generally be the caller's responsibility to call close
there).
If you don't have access to the source code and want to see whether your reader and JVM calls close
on the various readers and streams in your situation, you could override the close
method as a simple test.
Path path = Paths.get("/home/example/test.txt");
InputStream fileInputStream = new FileInputStream(path.toFile()) {
public void close() throws IOException {
System.out.println("FileInputStream::close()");
super.close();
}
};
Reader inputStreamReader = new InputStreamReader(fileInputStream, Charsets.UTF_8) {
public void close() throws IOException {
System.out.println("InputStreamReader::close()");
super.close();
}
};
BufferedReader bufferedReader = new BufferedReader(inputStreamReader) {
public void close() throws IOException {
System.out.println("BufferedReader::close()");
super.close();
}
};
bufferedReader.close();
When you run the above, you'll see something very similar to:
BufferedReader::close()
InputStreamReader::close()
FileInputStream::close()
Since there is no explicit specification written in the JavaDoc, we can't be certain of the behavior across all JVMs. However, most of readers/streams seem to follow the above pattern (e.g. you can add a GZIPInputStream
to the above example and see that GZIPInputStream::close()
also gets called).