14

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)?

Dave
  • 13,518
  • 7
  • 42
  • 51
  • Of course if the `BufferedReader` constructor throws, you wont be able to close the underlying `FileReader` (which you can't specify the charset for anyway, so is a bit hopeless itself). – Tom Hawtin - tackline Sep 25 '09 at 16:19

4 Answers4

19

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 the close() method on the GZIPOutputStream 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 Readers, even though it may not explicitly say so.

Community
  • 1
  • 1
coobird
  • 159,216
  • 35
  • 211
  • 226
  • 1
    True (modulo [bugs](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6266377)) but consider : http://stackoverflow.com/a/3629116/281545. So if `CryptOutputStream` threw `IOException` in your example shouldn't the caller close `fos` anyway ? – Mr_and_Mrs_D May 03 '13 at 15:47
4

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.

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
0

Yes. It does. I found this out when using it for sockets.

My Question

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. :-(

Community
  • 1
  • 1
Alex
  • 6,843
  • 10
  • 52
  • 71
0

Yes, this is the Decorator pattern.

rodrigoap
  • 7,405
  • 35
  • 46