Java IO - closing input streams

If

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

closes fileIS automatically closes dataIS because dataIS propagates fileIS or if dataIS also closes separately?

thanks

+4
source share
4 answers

If given a choice, you should close only DataInputStream . In general, always close the external wrapper thread. The closure will extend inward, and this is the only way to ensure proper behavior in general.

However, if you close the underlying FileInputStream , this will also be enough, because the DataInputStream itself does not receive any system resources.

The most direct answer to your question: no, closing the underlying thread does not close the wrapper thread, but in practice this has nothing to do with the prospects of leaking system resources. Only the stream at the bottom is associated with a real system resource.

+7
source

The converse must be done. Since the DataInputStream wraps a FileInputStream, you must close it, which will also close the FileInputStream.

+2
source

The implementation will take care of closing internal threads. Close the main outter stream, otherwise you may get problems when using, for example, BufferedOutputStream and you first close OutputStream - the data remaining in the buffer cannot be written and lost!

+2
source

DataInputStream extends FilterInputStream and does not implement close () at all, therefore it is inherited. The behavior you are asking for is explicitly stated in the contract for FilterInputStream.close (), so DataInputStream must obey, like all other derived FilterInputStream classes. Similarly for the FilterOutputStream, FilterReader, and FilterWriter derived classes.

0
source

Source: https://habr.com/ru/post/1439471/


All Articles