Read/convert an InputStream to a String
If you have
java.io.InputStream
object, how should you process that object and produce a String
?
Suppose I have an
InputStream
that contains text data, and I want to convert this to a String
(for example, so I can write the contents of the stream to a log file).
What is the easiest way to take the
InputStream
and convert it to a String
?public String convertStreamToString(InputStream is) {
// ???
}
Answer:
A nice way to do this is using Apache commons
IOUtils
to copy the InputStream
into a StringWriter
... something likeStringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
or even
// NB: does not close inputStream, you can use IOUtils.closeQuietly for that
String theString = IOUtils.toString(inputStream, encoding);
Alternatively, you could use
ByteArrayOutputStream
if you don't want to mix your Streams and Writers
http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string