Read/convert an InputStream to a String


If you have 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) { 
    // ???

Johnny Maelstrom


Here’s a way using only standard Java library (note that the stream is not closed, YMMV).

static String convertStreamToString( is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? : "";

I learned this trick from “Stupid Scanner tricks” article. The reason it works is because Scanneriterates over tokens in the stream, and in this case we separate tokens using “beginning of the input boundary” (\A) thus giving us only one token for the entire contents of the stream.

Note, if you need to be specific about the input stream’s encoding, you can provide the second argument to Scanner constructor that indicates what charset to use (e.g. “UTF-8”).

Hat tip goes also to Jacob, who once pointed me to the said article.

EDITED: Thanks to a suggestion from Patrick, made the function more robust when handling an empty input stream. One more edit: nixed try/catch, Patrick’s way is more laconic.

Pavel Repin

Stack Overflow