amphibient
amphibient

Reputation: 31212

Java IO -- closing input streams

If

FileInputStream fileIS = new FileInputStream(filePathStr);
DataInputStream dataIS = new DataInputStream(fileIS);

does closing fileIS automatically close dataIS since dataIS is propagated fileIS or should dataIS also be closed separately?

Thanks

Upvotes: 2

Views: 358

Answers (4)

user207421
user207421

Reputation: 310860

DataInputStream extends FilterInputStream and does not itself implement close() at all, so it is inherited. The behaviour you are asking about is explicitly specified in the contract for FilterInputStream.close(), which DataInputStream therefore must obey, as must all other derived classes of FilterInputStream. Similarly for derived classes of FilterOutputStream, FilterReader, and FilterWriter.

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200148

If given choice, you should close only the DataInputStream. More generally, always close the outermost wrapper stream. The closing will propagate inwards and this is the only way to generally ensure correct behavior.

However, if you close the underlying FileInputStream, that will also be enough because the DataInputStream doesn't by itself acquire any system resources.

The most direct answer to your question: no, closing the underlying stream does not close the wrapper stream, but in practice that is irrelevant from the perspective of system resource leaks. Only the stream at the bottom is coupled to the actual system resource.

Upvotes: 6

Manuel
Manuel

Reputation: 4228

The implementation will take care of closing the inner streams. Close the outter most stream, otherwise you can get problems when using an e.g. BufferedOutputStream and you close the OutputStream first - the data remaining within the buffer cannot be written and is lost!

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691635

The reverse should be done. Since the DataInputStream wraps the FileInputStream, you should close it, which would also close the FileInputStream.

Upvotes: 2

Related Questions