blackSmith
blackSmith

Reputation: 3154

Does stream.close closes any enclosing streams

AFAIK, a call to the close on a stream(I/O) closes any underlying streams including itself.
Is the reverse true ?

For example :

InputStream inStream = new FileInputStream("abc.txt"); 
BufferedInputStream bin = new BufferedInputStream(inStream);
inStream.close();  

Will this closes bin also ?
If not, is there any need to do so ? ie : will it cause a memory leak ?

Upvotes: 1

Views: 531

Answers (2)

Stephen C
Stephen C

Reputation: 718816

Will this closes bin also ?

No. (The wrapped InputStream doesn't have a reference to the BufferedInputStream. It couldn't close it, even if it "wanted" to.)

If not, is there any need to do so ?

Not really. (However, it is good practice to close the wrapper stream rather than the wrapped stream ... because of the "output" case; see below.)

ie : will it cause a memory leak ?

Definitely, no. And not a resource leak either:

  • From the above, the BufferedInputStream is not reachable from the InputStream, and therefore operations on the latter cannot affect the reachability of the former.

  • The BufferedInputStream does not "own" any external resources (e.g. file descriptors). They are owned and managed by the InputStream.


The answer would be a bit different for a BufferedOuputStream wrapping an OutputStream. If you closed the wrapped OutputStream directly, you could lose data in the buffer that has not been flushed.

Upvotes: 1

icza
icza

Reputation: 417622

Will this closes bin also ?

The enclosed stream can't close the enclosing stream because it doesn't know about it.

If not, is there any need to do so? ie : will it cause a memory leak ?

It will not cause a memory leak because the resources are allocated / held by the enclosed stream and are freed properly when it is closed, but the enclosing stream may implement buffering and other translation logic which if not flushed or closed, the data actually written to the enclosed stream might be incomplete/corrupt.

So it is always recommended to flush the enclosing stream (preferred would be to close that, but if you can't, the minimum you should do is flush it).

Flushing the enclosing stream is not always enough because for the underlying stream to contain valid data, the enclosing stream might add additional padding or formatting. An example for this is ZipOutputStream which in order to provide a valid zip file (zip format), it provides the ZipOutputStream.finish() method which besides flushing also writes additional zip-file related data (and does not close the underlying stream).

You might find this useful:

Close Encapsulating Writers/Streams for ServletOutputStream

Upvotes: 2

Related Questions