Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to close an InputStream in Java?

My code is:

InputStream confFile=classLoader.getResourceAsStream("myconffile.properties"); 

In docs:

The close method of InputStream does nothing.

Does it mean that I don't need close InputStream?

like image 230
user710818 Avatar asked Mar 03 '12 16:03

user710818


People also ask

Do we need to close ByteArrayInputStream in Java?

You don't have to close ByteArrayInputStream , the moment it is not referenced by any variable, garbage collector will release the stream and somebytes (of course assuming they aren't referenced somewhere else).

Does Java automatically close the file input stream?

An FileInputStream and a BufferedInputStream . Both of these resources will be closed automatically when execution leaves the try block.


2 Answers

You do need to close the input Stream, because the stream returned by the method you mention is actually FileInputStream or some other subclass of InputStream that holds a handle for a file. If you do not close this stream you have resource leakage.

like image 194
Boris Strandjev Avatar answered Oct 08 '22 10:10

Boris Strandjev


No, it does not mean that - because InputStream is an abstract class, and getResourceAsStream() returns a concrete subclass whose close() method does something - most importantly free a file handle.

like image 28
Michael Borgwardt Avatar answered Oct 08 '22 10:10

Michael Borgwardt