How do I convert an InputStream to a String in Java?

Viewed 17325

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) { 
    // ???
}
6 Answers

Since Java 9 InputStream.readAllBytes() even shorter:

String toString(InputStream inputStream) throws IOException {
   return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); // Or whatever encoding
}

Note: InputStream is not closed in this example.

Related