Convert InputStream to a String in Java

In this post, you will learn to convert InputStream to a String in 5 ways.

We use the InputStream class to read some data from a file. Data will be transformed into an ordered stream of bytes.

You might also be interested in learning how to read a file in Java.

As it was mentioned earlier, there are many ways to convert InputStream to a String in Java. Here, we will cover the following ways:

  • Using the Scanner class
  • With the InputStream.readAllBytes() method
  • Using the StringBuilder class together with InputStreamReader
  • With the IOUtils.toString() method
  • Using the CharStreams class

Convert InputStream into a String in Java using the Scanner class

The first way is to use the standard Scanner class. 

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

class ConvertInputStreamToString {

  public static void main(String[] args) {

    String resultString;
    String str = "Some String";
    // create InputStream using the bytes from the above String
    InputStream inputStream = new ByteArrayInputStream(str.getBytes());

    // Convert data from InputStream into a new String
    try (Scanner scanner = new Scanner(inputStream).useDelimiter("\\A")) {
      resultString = scanner.hasNext() ? scanner.next() : "";
    }

    System.out.println(resultString);

  }
}
Output: Some String
 
Here, we put the creation of the Scanner object into a try-with-resources because we want to close the Scanner after it reads all the data. We passed the “\\A” to tell the Scanner to read the entire input stream.

With the InputStream.readAllBytes() method

We can use the readAllBytes() method of the InputStream class. This method got introduced in Java 9.

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

class ConvertInputStreamToString {

  public static void main(String[] args) throws IOException {

    String str = "Some String";
    InputStream inputStream = new ByteArrayInputStream(str.getBytes());

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

    System.out.println(resultString);

  }
}
Output: Some String

Parse InputStream to a String using the StringBuilder class together with InputStreamReader

The StringBuilder class can be used for converting the InputStream into a String. We also need to use the InputStreamReader class to create a Reader object.

import java.io.*;
import java.nio.charset.StandardCharsets;

class ConvertInputStreamToString {

  public static void main(String[] args) throws IOException {

    int bufferSize = 1024;
    char[] buffer = new char[bufferSize];

    String str = "Some String";
    InputStream inputStream = new ByteArrayInputStream(str.getBytes());

    StringBuilder strBuilder = new StringBuilder();

    try (Reader in = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {

      for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) {
        strBuilder.append(buffer, 0, numRead);
      }
    }

    System.out.println(strBuilder.toString());

  }
}
Output: Some String

With the IOUtils.toString() method

The IOUtils class belongs to the Apache Commons library. We need to add the following Maven dependency to the pom.xml:

<dependency>
    <groupid>commons-io</groupid>
    <artifactid>commons-io</artifactid>
    <version>2.11.0</version>
</dependency>

Example

import java.io.*;
import java.nio.charset.StandardCharsets;

class ConvertInputStreamToString {

  public static void main(String[] args) throws IOException {

    String str = "Some String";
    InputStream inputStream = new ByteArrayInputStream(str.getBytes());

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

    System.out.println(resultString);
  
  }
}
Output: Some String

With the CharStreams class

The CharStreams class belongs to the Guava library. It has a toString() method that we can use to parse InputStream to a String.

To be able to use it, we need to add the following Maven dependency:

<dependency>
    <groupid>com.google.guava</groupid>
    <artifactid>guava</artifactid>
    <version>31.0.1-jre</version>
</dependency>


Example

import com.google.common.io.CharStreams;
import org.apache.commons.io.Charsets;
import java.io.*;

class ConvertInputStreamToString {

  public static void main(String[] args) throws IOException {

    String str = "Some String";
    InputStream inputStream = new ByteArrayInputStream(str.getBytes());

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

    System.out.println(resultString);
  
  }
}
Output: Some String
 
That’s it!

Leave a Reply

Your email address will not be published.