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

2

8

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?

Slipon answered 26/4, 2016 at 10:3 Comment(3)
No need to close inputstreams as such, We explicitly have to close outputstreams, you can close it if you want to, can you provide which issue you are facing ?Chervil
I'm not facing any issue. I always have problems to understand when and why I should close streams. I saw the pice of code to convert an InputStream to a virtual File without close the InputStream. So I was thinking if should be needed to close it.Slipon
After re consideration, I think we should close it, as it will contain the pointer/handle to our file, offset till which it has read the contents of the file, and other information regarding the same. If we close it then we are releasing the resource making program efficient.Chervil
G
11

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.

Galligaskins answered 26/4, 2016 at 10:16 Comment(0)
C
1

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.

Conscious answered 26/4, 2016 at 10:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.