Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I close the InputStream of org.apache.commons.io.IOUtils

I'm using the answer on How to convert InputStream to virtual File which uses org.apache.commons.io.IOUtils to copy the given InputStream to a FileOutputStream in order to create a File.

Should I close the InputStream given?

like image 307
ilopezluna Avatar asked Apr 26 '16 10:04

ilopezluna


People also ask

Do I need to close an InputStream?

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.

What happens if you don't close InputStream?

The operating system will only allow a single process to open a certain number of files, and if you don't close your input streams, it might forbid the JVM from opening any more.

Why do we close InputStream in Java?

The java. io. InputStream. close() method closes this stream and releases any system resources associated with the stream.

Does IOUtils copy close the stream?

Applications can re-use buffers by using the underlying methods directly. This may improve performance for applications that need to do a lot of copying. Wherever possible, the methods in this class do not flush or close the stream.


1 Answers

It is a best practice to close InputStream. See this question.

org.apache.commons.io.IOUtils.copy do not close streams. So you have to close.

See Javadoc

Wherever possible, the methods in this class do not flush or close the stream. This is to avoid making non-portable assumptions about the streams' origin and further use. Thus the caller is still responsible for closing streams after use.

like image 148
Adisesha Avatar answered Sep 30 '22 18:09

Adisesha