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)?
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)?
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 theGZIPOutputStream
class.
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 Reader
s, 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.
Yes. It does. I found this out when using it for sockets.
Basically you just can't close it until you are done with the parent. In the case of sockets this will actually close your socket. :-(