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

Submitted 3 years, 6 months ago
Ticket #237
Views 206
Language/Framework Java
Priority Low
Status Closed

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) {
    // ???
}
Submitted on Oct 19, 20
add a comment

2 Answers

From Java9:

public String convertStreamToString(InputStream is) {
  return new String(is.readAllBytes(),StandardCharsets.UTF_8);
}

Submitted 3 years, 6 months ago


Verified

Copy the InputStream into a StringWriter... something like

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

or even

// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding); 

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

Submitted 3 years, 6 months ago


Latest Blogs