JavaTechnology

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 useful when we read. For example, reading a content of a file, or reading a content of a Http Response. In this tutorial we will see the ways we can read bytes from Input stream as a String.

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

Create InputStream from a String

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

String string = "This is my test String";
InputStream stringIs = new ByteArrayInputStream(string.getBytes(UTF_8));

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

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

Using Apache Commons IO

The most simple way of converting a String to an InputStream is by making use of Apache Commons IO library. The library provides many useful abstractions for File IO.

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

String string = IOUtils.toString(stringIs, UTF_8);

Using Guava

Next, we will see how can we 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 done. Thus, we are using try-with-resource here.

try (Reader reader = new InputStreamReader(stringIs)) {
    String string = CharStreams.toString(reader);
}

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();

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"));

In the Stream collector, we are joining the strings using 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, without Java Streams approach, 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();

Using Plain Java Scanner

Next, we will see 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();

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 a various ways of Converting InputStream to String in Java. We have seen that, using the Plain Java approach 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 quite concise and easy to use. For more on Java please visit: Java Tutorials.