40

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.

Freewind
  • 193,756
  • 157
  • 432
  • 708

2 Answers2

42

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.

Anders Rabo Thorbeck
  • 1,126
  • 3
  • 18
  • 28
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

Yes, and InputStream is now AutoCloseable so you can do:

try(InputStream input = getInputStream()) 
Cybermonk
  • 514
  • 1
  • 6
  • 28