How to Convert InputStream to String in Java

Very frequent situation: you have java.io.InputStream and you need to convert it in some way into a String.

There are several approaches to achieve this in Java, I’ll show you the best of them in this article.

Using Apache Commons IOUtils

Probably the easiest way to transform InputStream into String is by using Apache commons IOUtils to copy the InputStream into a StringWriter:

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer,  StandardCharsets.UTF_8);
String str = writer.toString();

Or you can even write it in one line:

String str = IOUtils.toString(inputStream,  StandardCharsets.UTF_8);

It’s important to notice that after converting the inputStream will still remain opened, don’t forget to close it by IOUtils.closeQuietly() method.

 

Using Standard Java Library Scanner

If you don’t want to use any external library then you can use Scanner class from Java standard library.

static String inputStreamToString(java.io.InputStream inputStream) {
    java.util.Scanner scanner = new java.util.Scanner(inputStream).useDelimiter("\\A");
    return scanner.hasNext() ? scanner.next() : "";
}

 

Using Standard Java Library BufferedInputStream and ByteArrayOutputStream

BufferedInputStream buffIS = new BufferedInputStream(inputStream);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int result = buffIS.read();
while(result != -1) {
    outputStream.write((byte) result);
    result = buffIS.read();
}
return outputStream.toString("UTF-8");

 

Using Standard Java Library InputStreamReader and StringBuilder

final int bufferSize = 1024;
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(inputStream, "UTF-8");
for (; ; ) {
    int rsz = in.read(buffer, 0, buffer.length);
    if (rsz < 0)
        break;
    out.append(buffer, 0, rsz);
}
return out.toString();

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.