Convert InputStream to a String in Java

In this post, you will learn to convert InputStream to a String in 5 different 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

1. Convert InputStream into a String 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.

2. Using 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 {

    /**
     * This method shows how to convert InputStream to a String using an array of bytes and specifying the charset.
     */
    public static void main(String[] args) throws IOException {

        String str = "Some String";
        InputStream inputStream = new ByteArrayInputStream(str.getBytes());
        byte[] byteArray = inputStream.readAllBytes();
        // Convert data from byteArray into a new String
        String resultString = new String(byteArray, StandardCharsets.UTF_8);

        System.out.println(resultString);
    }
}
Output: Some String
 
Here, we are using the InputStream.readAllBytes() method to read all the bytes from the InputStream and store it into a byte array. Then we are using the new String constructor that takes an array of bytes and the charset (StandardCharsets.UTF_8) as a parameter and converts it to a string, you can learn how to do this type of conversion in this tutorial Converting byte[] Array to String in Java

3. Parse InputStream to a String using the StringBuilder

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

4. Using 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;
import org.apache.commons.io.IOUtils;

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

5. Using 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
 

Leave a Reply

Your email address will not be published. Required fields are marked *