How to convert InputStream to String in Java

August 23, 2020 No comments Java IO Conversions InputStream String

1. Introduction

In this tutorial, we are going to learn how to convert an InputStream to a String in Java using plain Java, Guava, and Apache Commons IO library. Converting operations are very common requirements in many Java applications that process external resources from the filesystem or web.

For more Java I/O related articles, check the following links:

2. InputStream to a String using ByteArrayOutputStream

Using a ByteArrayOutputStream is a plain Java approach to convert InputStream to a String.

package com.frontbackend.java.io.conversions;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class InputStreamToStringUsingByteArrayOutputStream {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream("/tmp/frontbackend.txt"); // inputStream for testing

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int length;
        byte[] data = new byte[1024];

        while ((length = inputStream.read(data)) != -1) {
            outputStream.write(data, 0, length);
        }

        String text = outputStream.toString(StandardCharsets.UTF_8.name());

        System.out.println(text);
    }
}

First we read bytes from the InputStream in blocks and then write them to ByteArrayOutputStream that contains method toString() which could be used to get String with the content.

Note that we might also get byte array from the ByteArrayOutputStream and use it to create a String like in the following example:

byte[] byteArray = outputStream.toByteArray();
String text = new String(byteArray, StandardCharsets.UTF_8);

3. Converting InputStream to a String using BufferedReader

Using BufferedReader is another way to convert an InputStream to a String in Java. This approach gives us the ability to read the stream line by line.

package com.frontbackend.java.io.conversions;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamToStringUsingBufferedReader {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream("/tmp/frontbackend.txt");

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder out = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            out.append(line);
        }
        System.out.println(out.toString());
        reader.close();
    }
}

In this example, we used BufferedReader to read InputStream line by line using InputStreamReader. StringBuilder is used to append each line to the output String.

4. InputStream to String using Guava library

Another way to convert InputStream to a String is to use external library Guava that comes with very useful utility classes and methods to perform IO operations.

First add Guava dependency into your project, available versions can be found here: com.google.guava:guava.

Note that there is a seperate library version for JRE and Android. The Android version of Guava is optimized for use on Android.

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>28.2-jre</version>
</dependency>

In the following example used ByteSource functionality from the Guava library:

package com.frontbackend.java.io.conversions;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.google.common.base.Charsets;
import com.google.common.io.ByteSource;

public class InputStreamToStringUsingGuava {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream("/tmp/frontbackend.txt");

        ByteSource byteSource = new ByteSource() {
            @Override
            public InputStream openStream() throws IOException {
                return inputStream;
            }
        };

        String text = byteSource.asCharSource(Charsets.UTF_8)
                                .read();

        System.out.println(text);
    }
}

In this example we view the ByteSource with our InputStream as a CharSource with UTF8 charset and the use read() method to read it as a String.

Luckily there is an easies way to do the conversion using Guava's CharStreams:

package com.frontbackend.java.io.conversions;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import com.google.common.io.CharStreams;

public class InputStreamToStringUsingGuavaCharStreams {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream("/tmp/frontbackend.txt");

        final String text;

        try (final Reader reader = new InputStreamReader(inputStream)) {
            text = CharStreams.toString(reader);
        }

        System.out.println(text);
    }
}

In this example, we used try-with-resources syntax to automatically close the stream but Guava gives us some other great utility class that could be used to close streams:

Closeables.closeQuietly(inputStream);

5. Converting InputStream to String with Apache Commons IO

Conversion from the InputStream to String can be also achieved using Apache Commons IO library. Let's start by adding a dependency to our project. The latest version of the library can be found under the following link: commons-io:commons-io

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

There are two approaches when using the Apache Commons IO library:

  • we can use IOUtils.copy() method or,
  • IOUtils.toString() method.

The following example shows how to use IOUtils.copy method:

package com.frontbackend.java.io.conversions;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

import org.apache.commons.io.IOUtils;

public class InputStreamToStringUsingIOUtilsCopy {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream("/tmp/frontbackend.txt");

        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, "UTF-8");
        String text = writer.toString();

        System.out.println(text);
    }
}

The next example presents IOUtils.toString - a method, that allows us to convert InputStream into String in one line:

package com.frontbackend.java.io.conversions;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.IOUtils;

public class InputStreamToStringUsingIOUtilsToString {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream("/tmp/frontbackend.txt");

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

        System.out.println(text);
    }
}

Keep in mind that neither copy nor toString methods from Apache Commons IO closes the stream, so you have to do it 'manually'.

6. Java InputStream to String using Scanner

To convert an InputStream to a String we can also use Scanner class that comes with java.util package. Scanner iterates over tokens in a stream and by separating tokens using The beginning of the input - (A) we will get the whole content of the stream.

package com.frontbackend.java.io.conversions;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class InputStreamToStringUsingScanner {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream("/tmp/frontbackend.txt");

        Scanner scanner = new Scanner(inputStream, "UTF-8").useDelimiter("\\A");
        String text = scanner.hasNext() ? scanner.next() : "";

        System.out.println(text);
        scanner.close();
    }
}

Closing the scanner scanner.close() automatically closing the stream. We could also use try-with-resources that will close scanner implicitly:

try (Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
    text = scanner.useDelimiter("\\A").next();
}

7. Converting InputStream to String using java.nio.Files class

Another way to get the content of the InputStream and put it into a String is to use Files class that is available under the new Java NIO API:

package com.frontbackend.java.io.conversions;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

public class InputStreamToStringUsingFiles {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream("/tmp/frontbackend.txt");

        Path tempFile = Files.createTempFile(UUID.randomUUID()
                                                 .toString(),
                UUID.randomUUID()
                    .toString());
        Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
        String text = new String(Files.readAllBytes(tempFile));

        System.out.println(text);
    }
}

In this solution first, we need to create a temporary file and copy there the content from the InputStream. Then, we could use Files.readAllBytes method to read the content of the file and put it into a String.

8. InputStream to String conversion using Java 9 InputStream.readAllBytes() method

Since Java 9 we can readAllByte straight from the InputStream using readAllBytes method:

package com.frontbackend.java.io.conversions;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class InputStreamToStringUsingFiles {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = new FileInputStream("/tmp/frontbackend.txt");

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

        System.out.println(text);
    }
}

9. Conclusion

In this article, we presented approaches to convert InputStream to a String in Java. You should choose the best solution that suits you and will not generate any unnecessary conflicts in your project.

All examples used in this article can be found on the GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}