Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

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?

public String convertStreamToString(InputStream is) {

    // ???

}

1 Answer

0 votes
by (46k points)

A right way to do this is applying Apache commons IOUtils to copy the InputStream within a StringWriter... something like

StringWriter writer = new StringWriter();

IOUtils.copy(inputStream, writer, encoding);

String theString = writer.toString();

Also

// NB: does not close inputStream, you'll have to use try-with-resources for that

String theString = IOUtils.toString(inputStream, encoding); 

Alternatively, you could apply ByteArrayOutputStream if you don't want to tangle your Streams and Writers

Related questions

Browse Categories

...