Ignasi
Ignasi

Reputation: 6185

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?

Upvotes: 8

Views: 6196

Answers (2)

Diyarbakir
Diyarbakir

Reputation: 2099

Edit: After reading the question again I have to correct my answer because the question apparently was about the InputStream from the referenced answer and not the OutputStream. The InputStream needs to be closed (see the answer from @Adi). The OutputStream however is in the try-with-resources Statement so that's the one you don't need to close.

The answer that is referenced in the question is using the Java 7 try-with-resources Statement which ensures that the resource is closed at the end of the statement.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.

So for the OutputStream, NO, in that particular case you don't need to close the OutputStream yourself, provided you are using try-with-resource.

The InputStream however needs to be closed.

Upvotes: 1

Adisesha
Adisesha

Reputation: 5258

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.

Upvotes: 11

Related Questions