Skip to content
Advertisement

How do I read / convert an InputStream into a String in Java?

If you have a 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 it to a String, so for example I can write that to a log file.

What is the easiest way to take the InputStream and convert it to a String?

JavaScript

Advertisement

Answer

A nice way to do this is using Apache Commons IOUtils to copy the InputStream into a StringWriter… Something like

JavaScript

or even

JavaScript

Alternatively, you could use ByteArrayOutputStream if you don’t want to mix your Streams and Writers.

Advertisement