Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to close the input stream manually after using IOUtils.toString(input) of commons-io?

Commons-IO has an IOUtils.toString(inputStream) method, which can read all content from an input stream:

InputStream input = getInputStream();
String content = IOUtils.toString(input);

My question is shall I close the input stream manually after using it?

I thought IOUtils may close it since it has read all the content, but I can't find that in the source code.

like image 643
Freewind Avatar asked Dec 07 '13 15:12

Freewind


People also ask

Do you have to close an input stream?

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.

Which method is used to close input stream?

skips() - skips and discards the specified number of bytes from the input stream. close() - closes the input stream.

What does Ioutils copy do?

Copies chars from a Reader to bytes on an OutputStream using the specified character encoding, and calling flush. Copies chars from a Reader to a Writer .


1 Answers

The javadoc says:

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 171
JB Nizet Avatar answered Oct 07 '22 00:10

JB Nizet