Convert InputStream to String in Java

While writting Java programs much time we need to convert an InputStream object to a String. There are many ways to do this, we can use core Java classes or we can use some really good java libraries to convert InputStreams to String.

Apart from JDK, Apache Commons IO, and Guava provides classes to convert/read InputStream to string.

Apache commons-io and Guava lib can be easily added to the project via Gradle or maven and you can use any of these.

<!-- -->

<!-- -->

implementation group: '', name: 'guava', version: '30.1.1-jre'

implementation group: 'commons-io', name: 'commons-io', version: '2.8.0'

Converting InputStream to String Using IOUtils of Apache common-io

try (InputStream inputStream = new FileInputStream(new File("C:\\test.txt"))) {
    // Method 1
    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, StandardCharsets.UTF_8);

    // Method 2
    // Do not forget to close stream
    System.out.println(IOUtils.toString(inputStream, StandardCharsets.UTF_8));

Using Guava Lib

String result = CharStreams.toString(new InputStreamReader(
        inputStream, Charsets.UTF_8));

There are many other methods using JDK 8 and 9

Jdk 9 introduced readAllBytes method, that can also be used to read all bytes and convert them to string as given below.

String result = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);

Using JDK ByteArrayOutputStream is fasted in reading a string from an input file stream. Please check the below example.

ByteArrayOutputStream result = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            for (int length; (length = != -1; ) {
                result.write(buffer, 0, length);
            // > JDK 7
            System.out.println( result.toString("UTF-8"));

Leave a Reply

Your email address will not be published. Required fields are marked *

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