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

If you want to do it simply and reliably, I suggest using the Apache Jakarta Commons IO library IOUtils.toString(java.io.InputStream, java.lang.String) method.


String text = new Scanner(inputStream).useDelimiter("\\A").next();

The only tricky is to remember the regex \A, which matches the beginning of input. This effectively tells Scanner to tokenize the entire stream, from beginning to (illogical) next beginning...
- from the Oracle Blog


This is my version,

public static String readString(InputStream inputStream) throws IOException {

    ByteArrayOutputStream into = new ByteArrayOutputStream();
    byte[] buf = new byte[4096];
    for (int n; 0 < (n = inputStream.read(buf));) {
        into.write(buf, 0, n);
    }
    into.close();
    return new String(into.toByteArray(), "UTF-8"); // Or whatever encoding
}

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.