Convert InputStream to String

JavaJavaBeginner
Practice Now

Introduction

In Java, the InputStream class is used to read data from files in an ordered sequence. To use the data as a string, we need to convert the InputStream to a String. This lab will teach you different ways to convert an InputStream to a string.

Using InputStreamReader

The InputStreamReader class provides a read() method to read data from an InputStream into a character array. We can convert the char array to a string. Create a new Java source file InputStreamToString.java in the ~/project directory with the following content:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        InputStreamReader reader = new InputStreamReader(input);
        char[] charArray = new char[256];
        reader.read(charArray);
        return new String(charArray);
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

To run the code, open the terminal, then compile and run the code with the following command:

javac InputStreamToString.java && java InputStreamToString

Using InputStreamReader and BufferedReader with StringBuilder

The previous step can be inefficient for larger inputs. Instead, we can use a BufferedReader to wrap the InputStreamReader to improve efficiency. Then, we will use a StringBuilder object to append the lines read from the BufferedReader. Create a new step in InputStreamToString.java after Step 1 with the following code:

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

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        StringBuilder builder = new StringBuilder();
        InputStreamReader reader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

Using InputStreamReader and BufferedReader without StringBuilder

We can use a simpler approach by using the lines() method of the BufferedReader class. This allows us to skip appending each line to a separate StringBuilder instance. Create a new step in InputStreamToString.java after Step 2 with the following code:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        InputStreamReader reader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String str = bufferedReader.lines().collect(Collectors.joining("\n"));
        return str;
    }

    public static void main(String[] args) {
        InputStream input = new ByteArrayInputStream("hello world".getBytes());
        String strFromInputStream = inputStreamToString(input);
        System.out.print("String from the Input Stream is: " + strFromInputStream);
    }
}

Using the readAllBytes() method of the InputStream

The InputStream class introduced the readAllBytes() method in Java 9. This can efficiently convert the entire InputStream object to a string in a single line of code. However, this method is not recommended for larger inputs. Create a new step in InputStreamToString.java after Step 3 with the following code:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        return new String(input.readAllBytes());
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

Using the Scanner Class

We can also use the Scanner class, a commonly used class for reading and parsing data, to convert the input stream to a string. Create a new step in InputStreamToString.java after Step 4 with the following code:

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

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        Scanner scanner = new Scanner(input);
        StringBuilder builder = new StringBuilder();
        while (scanner.hasNext()) {
            builder.append(scanner.nextLine());
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

Using ByteArrayOutputStream

We can use the ByteArrayOutputStream class in the java.io package and copy data from the input stream to the byte array. Then, we can write the byte array to the ByteArrayOutputStream. Finally, we will use the toString() method of the ByteArrayOutputStream to get the string representation. Create a new step in InputStreamToString.java after Step 5 with the following code:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[128];
        int length;
        while ((length = input.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        return byteArrayOutputStream.toString();
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

Using java.nio Package

In the java.nio package, we can create a temporary file using Files.createTempFile and copy the data from the InputStream to this file. Then, we can read the content of this temporary file into a string. Create a new step in InputStreamToString.java after Step 6 with the following code:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        Path file = Files.createTempFile(null, null);
        Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING);
        return new String(Files.readAllBytes(file));
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);
        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

Using Google Guava Library

The Google Guava library provides the CharStreams class to convert an InputStream to a string. We can use the toString() method of this class to do this. It will take a Readable object (like the InputStreamReader) and read the data from it into a string. Create a new step in InputStreamToString.java after Step 7 with the following code:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.google.common.io.CharStreams;

public class InputStreamToString {
    public static String inputStreamToString(InputStream input) throws IOException {
        try(InputStreamReader reader = new InputStreamReader(input)) {
            return CharStreams.toString(reader);
        }
    }

    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = inputStreamToString(input);
            System.out.print("String from the Input Stream is: " + strFromInputStream);

        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

Using Apache Commons IO

The IOUtils class of the org.apache.commons.io package also contains a toString() method. We can directly pass the InputStream object to this method, and it will read the data from it into a string. We also need to specify a Charset. Create a new step in InputStreamToString.java after Step 8 with the following code:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;

public class InputStreamToString {
    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            String strFromInputStream = IOUtils.toString(input, StandardCharsets.UTF_8.name());
            System.out.print("String from the Input Stream is: " + strFromInputStream);

        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

Using StringWriter Class with Apache Commons IO

We can use the StringWriter class of the java.io package and copy the content of the InputStream into the StringWriter. We will use the copy() method of the IOUtils class. Create a new step in InputStreamToString.java after Step 9 with the following code:

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;

public class InputStreamToString {
    public static void main(String[] args) {
        try {
            InputStream input = new ByteArrayInputStream("hello world".getBytes());
            StringWriter sw = new StringWriter();
            IOUtils.copy(input, sw, StandardCharsets.UTF_8.name());
            String strFromInputStream = sw.toString();
            System.out.print("String from the Input Stream is: " + strFromInputStream);

        } catch(Exception e) {
            System.out.print(e);
        }
    }
}

Summary

In this lab, you learned different ways to convert an InputStream to a string in Java. You can use the ByteArrayOutputStream or the BufferedReader class to improve efficiency. The Scanner class is also available to convert the input stream to a string. The readAllBytes() method is suitable for smaller inputs only. We can use external libraries like the Google Guava or Apache Commons IO to simplify the process. Remember to handle exceptions and close the InputStream to avoid resource leaks.

Other Java Tutorials you may like