Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java IO -- closing input streams

Tags:

java

java-io

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

like image 576
amphibient Avatar asked Nov 23 '25 02:11

amphibient


2 Answers

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.

like image 147
Marko Topolnik Avatar answered Nov 25 '25 15:11

Marko Topolnik


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

like image 35
JB Nizet Avatar answered Nov 25 '25 15:11

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!