How to Convert InputStream to String

This article illustrates different ways to Convert InputStream to a String using Java, Apache Common IO, and Guava Library.

Overview

The InputStream is an abstract class in Java, and it represents a Stream of bytes. Input streams are helpful when we read. For example, reading the content of a file or reading the content of an HTTP Response. This tutorial will see how we can read bytes from the Input Stream as a String.

Before we do that, we will first see how to convert String to InputStream.

Create InputStream from a String

To convert a String to InputStream, we need to read all bytes of the String in the form of an array. Next, we will instantiate ByteArrayInputStream instance using the byte[].

String string = "This is my test String";
InputStream stringIs = new ByteArrayInputStream(string.getBytes(UTF_8));Code language: Java (java)

In the following examples, we will use the same InputStream and convert it into a String.

Next, we will see How to Read InputStream as a String.

Using Apache Commons IO

The most straightforward way of converting a String to an InputStream is by using Apache Commons IO library. The library provides many helpful abstractions for File IO.

We will use IOUtils#toString method and pass an instance of InputStream.

String string = IOUtils.toString(stringIs, UTF_8);Code language: Java (java)

Using Guava

Next, we will see how we can use Guava Library to achieve the same. To do that, we need to create an instance of InputStreamReader. Next, we will use CharStreams#toString and pass the reader instance to get the String.

However, we must close the reader once the conversion is complete. Thus, we are using try-with-resource here.

try (Reader reader = new InputStreamReader(stringIs)) {
    String string = CharStreams.toString(reader);
}Code language: Java (java)

Alternatively, we can Guava ByteSource by providing its anonymous implementation.

String string = (new ByteSource() {
    @Override
    public InputStream openStream() throws IOException {
            return stringIs;
        }
    })
    .asCharSource(UTF_8)
    .read();Code language: Java (java)

We created an anonymous implementation of the ByteSource, which wraps the InputStream. Next, we created a ByteSource view by applying the CharSet of UTF8. Finally, we read the string from the ByteSource.

Using Java Streams

Next, we will see how to use Java Streams to read String from InputStream. The lines method on the InputStreamReader class returns a Stream of Strings. Each String represents a single line from the InputStream. In our case, we do not have a multi-line string. Thus, the stream will have only one element.

String string = new BufferedReader(new InputStreamReader(stringIs, UTF_8))
        .lines()
        .collect(Collectors.joining("\n"));Code language: Java (java)

In the Stream collector, we join the strings using the new line character as a delimiter. Hence, our code will work with multiline Strings as well.

Using Plain Java BufferedReader

To convert InputStream to String in a plain Java fashion, we can read individual lines as String from the BufferedReader and append them using a StringBuilder.

StringBuilder builder = new StringBuilder();

try (BufferedReader bufferedReader = 
             new BufferedReader(new InputStreamReader(stringIs, UTF_8))) {
    String str;
    while ((str = bufferedReader.readLine()) != null) {
        builder.append(str);
    }
}

String string = builder.toString();Code language: Java (java)

Using Plain Java Scanner

Next, we will see the Java Scanner example to do the conversion.

StringBuilder builder = new StringBuilder();

try (Scanner scanner = new Scanner(stringIs, UTF_8)) {
    while (scanner.hasNext()) {
        builder.append(scanner.nextLine());
    }
}

String string = builder.toString();Code language: Java (java)

We are creating a Scanner instance using the InputStream and by providing the appropriate Charset. We are iterating through the scanner to get and append each line of String into a StringBuilder instance.

Summary

In this tutorial, we have seen various ways of Converting InputStream to String in Java. Using the Plain Java approach, we have seen that we need to manually iterate over the Strings, close the opened readers, or use try-with-resource blocks. However, the abstractions provided by Java Streams, Guava, and Apache Common IO library are pretty concise and easy to use. For more on Java, please visit Java Tutorials.