Say I do something like:
Reader r = new BufferedReader(new FileReader(file));
... read ...
r.close()
Does this close the underlying FileReader (and release the open file handle)?
The close() method of Reader Class in Java is used to close the stream and release the resources that were busy in the stream, if any. This method has following results: If the stream is open, it closes the stream releasing the resources. If the stream is already closed, it will have no effect.
close() method closes the input stream reader and invocations to read(), ready(), mark(), reset(), or skip() method on a closed stream will throw IOException.
The close() method closes a window.
When you are finished reading characters from the BufferedReader you should remember to close it. Closing a BufferedReader will also close the Reader instance from which the BufferedReader is reading.
Yes, calling close on the outer most Reader is going to be sufficient.
The Java I/O Streams article at the Sun Developer Network has a section on Stream Chaining which says the following:
FileOutputStream fos = new FileOutputStream("myfile.out"); CryptOutputStream cos = new CryptOutputStream(fos); GZIPOutputStream gos = new GZIPOutputStream(cos);[...]
[...] when closing chained streams, you only need to close the outermost stream class because the
close()call is automatically trickled through all the chained classes; in the example above, you would simply call theclose()method on theGZIPOutputStreamclass.
Therefore, in this case, one would only have to call close on the BufferedReader.
As dtsazza already mentioned, the Java API Specification for the BufferedReader class says that the BufferedReader.close method will free any underlying resources:
Closes the stream and releases any system resources associated with it. [...]
So, one can infer that any underlying Readers, even though it may not explicitly say so.
According to the documentation, it merely "releases any system resources associated with [the reader]". Whether a Reader closes any nested readers is a matter of the specific class' implementation.
In the specific example you mentioned - yes, a BufferedReader will always close the nested reader. But while this usually happens, this doesn't necessarily mean that all implementations of the Reader interface that have some sort of nested reader will propagate a close() call through to them - you'd need to check the documentation of that specific class to find out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With