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.

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1.1-jre</version>
</dependency>

// https://mvnrepository.com/artifact/com.google.guava/guava
implementation group: 'com.google.guava', name: 'guava', version: '30.1.1-jre'

// https://mvnrepository.com/artifact/commons-io/commons-io
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);
    System.out.println(writer.toString());

    // 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));
System.out.println(result);

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);
System.out.println(result);

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 = inputStream.read(buffer)) != -1; ) {
                result.write(buffer, 0, length);
            }
            // StandardCharsets.UTF_8.name() > 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.