Case 1:
BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(file) ) );
br.close();
Case 2:
BufferedReader br = new BufferedReader( new FileReader(file) );
br.close();
Case 3:
InputStream bis = new BufferedInputStream( new FileInputStream(src) );
bis.close();
What does close() do?
The docs say: "Closes the stream and releases any system resources associated with it."
Does it close any "underlying" resources also? Or would the correct code be to instantiate all the buffers and streams and close one by one?
4 Answers 4
Yes, the underlying resources are released. The Java IO stream classes are a good example of the Decorator pattern, i.e. an object that has an interface identical to an object it contains. This allows the close() method to be very simple and elegant, e.g. something like:
public void close() {
in.close();
}
If in is a decorator itself, its close method will close another resource, recursively.
If you're interested, java.io source code can be viewed online here.
Comments
Does it close any "underlying" resources also?
Yes
Or the correct code would be to instantiate all the buffers and streams and close one by one?
No, you don't need to do that.
I've always considered it a docs deficiency that this isn't explicitly stated. It is however implied by the words "any system resources associated with it". Since, even with an extra layer in the middle, your BufferedReader is still associated with a file, to conform to the doc it needs to recurse into its wrapped streams. Once those resources have been been released it's just a job for the garbage collector once your stream stops being referenced.
Comments
you only need to close the outer most stream class because the close() call is automatically trickled through all the chained classes.
public void close() throws IOException Description copied from class: Reader
Closes the stream and releases any system resources associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.
http://download.oracle.com/javase/6/docs/api/java/io/BufferedReader.html#close%28%29
1 Comment
Generally calls to close() will be cascaded down through underlying objects.