How To Convert InputStream To String In Java

This blog post is going to cover a topic that is crucial for all Java developers out there – how to convert InputStream to string in Java. As a developer, you must have come across the InputStream class, which is commonly used for reading input data from various sources.

However, there may be times when you need to convert an InputStream object to a String object. To help you better understand this process, we will discuss several methods to achieve this conversion.

These methods include using BufferedReader and StringBuilder, Scanner, ByteArrayOutputStream, and InputStreamReader. So, without further ado, let’s dive into how to convert InputStream to string in Java.

Why is there a need to convert InputStream to string in java?

In Java, an InputStream is a fundamental input stream of bytes from which data can be read in a sequential manner. A String, on the other hand, is a sequence of characters. There may be situations where you need to convert an InputStream to a String in JavaThe need to convert an InputStream to a String in Java arises in various situations.

  1. Compatibility: Some APIs only accept String input, so converting an InputStream to a String may be necessary to ensure compatibility with these APIs.
  2. Manipulation: Text data can be more efficiently manipulated and parsed when working with String objects, as opposed to InputStream objects.
  3. Convenience: In some cases, converting an InputStream to a String can simplify code and make it easier to read and maintain.

Four methods to convert InputStream to string in java?

Here’s a brief introduction to each of the four methods for converting an InputStream to a String in Java:

  1. Using BufferedReader and StringBuilder: This method involves creating a BufferedReader object to read the input stream, and a StringBuilder object to accumulate the data read from the stream. This approach is efficient and works well for larger input streams.
  2. Using Scanner: The Scanner class can also be used to read an InputStream and convert it to a String. This method is useful when parsing text data with delimiters.
  3. Using ByteArrayOutputStream: This method involves creating a ByteArrayOutputStream to write the contents of the input stream, and then converting the resulting byte array to String. This approach is very simple and works well for smaller input streams.
  4. Using InputStreamReader: This method involves creating an InputStreamReader object to read the input stream, and then reading the data character by character and adding it to a StringBuilder object. This approach is efficient and can handle different character encodings.

A thorough explanation of each strategy:

1. Using BufferReader and StringBuilder:

This method involves creating a BufferedReader object to read the input stream, and a StringBuilder object to accumulate the data read from the stream. The BufferedReader object reads the input stream line by line, while the StringBuilder object appends each line to the final String output.

Sample code:

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

public class InputStreamToStringExample {

    // Method to convert InputStream to String
    public static String convertStreamToString(InputStream inputStream) throws IOException {
        // Creating a new BufferedReader object to read the input stream
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        // Create a new StringBuilder object to accumulate the data read from the stream
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        // Read the input stream line by line using the BufferedReader object
        while ((line = bufferedReader.readLine()) != null) {
            // Append each line to the StringBuilder object
            stringBuilder.append(line).append("\n");
        }
        // Convert the StringBuilder object to a String and return the result
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        // Create a sample input stream using the ByteArrayInputStream class
        String sampleString = "This is an input stream.";
        InputStream inputStream = new ByteArrayInputStream(sampleString.getBytes());
        try {
            // Call the convertStreamToString method on the input stream and print the result
            String result = convertStreamToString(inputStream);
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

This is an input stream.

Code Explanation:

  1. First import the necessary classes: BufferedReader, InputStreamReader, InputStream, IOException, and ByteArrayInputStream.
  2. Define a class called InputStreamToStringExample.
  3. Define a static method called convertStreamToString() which takes an InputStream object as its parameter and returns a String.
  4. Create a new BufferedReader object to read the InputStream object passed as the method’s parameter. We also create a new StringBuilder object to accumulate the data read from the stream.
  5. Read the input stream line by line using the readLine() method of the BufferedReader object, and append each line to the StringBuilder object using the append() method.
  6. Convert the StringBuilder object to a String using the toString() method and return the result.
  7. In the main() method, we create a sample input stream using the ByteArrayInputStream class, which takes a String as an argument and converts it to a byte array input stream.
  8. Call the convertStreamToString() method on this input stream and print the result to the console using System.out.println().
  9. Also catch any IOException that may be thrown during the method call and print the stack trace.

2. Using Scanner:

The Scanner class can also be used to read an InputStream and convert it to a String. This method is particularly useful when parsing text data with delimiters. The Scanner class provides a convenient way to read data from various input sources and tokenize it based on a specified delimiter.

Sample code:


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

public class InputStreamToStringExample {
    public static void main(String[] args) {
        // Create a sample input stream
        String sampleString = "This is a demo sample input stream";
        InputStream inputStream = new ByteArrayInputStream(sampleString.getBytes());

        // Use Scanner to read the input stream and convert it to a String
        Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");
        String result = scanner.hasNext() ? scanner.next() : "";

        // Print the result
        System.out.println(result);
    }
}

Output:

This is a demo sample input stream

Code Explanation:

  1. First, we create a sample input stream using a string and convert it to an InputStream using the getBytes() method.
  2. Then create a new instance of the Scanner class and pass in the InputStream as a parameter.
  3. We use the useDelimiter(“\\A”) method to tell the Scanner to use the beginning of the input as the delimiter, effectively reading the entire stream at once.
  4. Then check if the Scanner has any more input using the hasNext() method, and if it does, we retrieve the next token using the next() method and store it in a String variable called result.
  5. Finally, we print out the contents of result

3. Using ByteArrayOutputStream:

This method involves creating a ByteArrayOutputStream to write the contents of the input stream, and then converting the resulting byte array to a String.

Sample code:

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

public class InputStreamToStringExample {

    public static void main(String[] args) throws IOException {
        // open an input stream to a file called "example.txt" 
        InputStream inputStream = InputStreamToStringExample.class.getResourceAsStream("example.txt");
        
        // call the convertInputStreamToString() method and print the result
        String result = convertInputStreamToString(inputStream);
        System.out.println(result);
    }

    // define the convertInputStreamToString() method to convert the input stream to a string
    private static String convertInputStreamToString(InputStream inputStream) throws IOException {
        // create a ByteArrayOutputStream to write the contents of the input stream to a byte array
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        
        // create a byte array buffer to read the input stream into
        byte[] buffer = new byte[1024];
        int length;
        // read the input stream into the buffer and write the contents of the buffer to the ByteArrayOutputStream
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        // convert the resulting byte array to a string using the "UTF-8" character encoding
        return result.toString("UTF-8");
    }
}

The output of the code will be the contents of the “example.txt” file, converted to a String:

Solution:

  1. We first import the necessary classes and define a public class called InputStreamToStringExample.
  2. Inside the InputStreamToStringExample class, we define a main() method that opens an input stream to a file called “example.txt” using the getResourceAsStream() method. This method is used to read resources that are stored in the same package as the class. You can replace this with any input stream that you want to convert to a string.
  3. We then call the convertInputStreamToString() method, passing in the input stream as a parameter, and print the resulting string to the console.
  4. The convertInputStreamToString() method is defined as a private static method that takes an InputStream as a parameter and returns a String.
  5. Inside the convertInputStreamToString() method, we create a ByteArrayOutputStream called result. This is used to write the contents of the input stream to a byte array.
  6. We also create a byte array called buffer of size 1024. This is used to read the input stream into.
  7. We then use a while loop to read the input stream into the buffer and write the contents of the buffer to the ByteArrayOutputStream result. This is done by calling the write() method of the ByteArrayOutputStream.
  8. Once the input stream has been fully read and written to the ByteArrayOutputStream, we convert the resulting byte array to a string using the “UTF-8” character encoding, and return the resulting string.

4. Using InputStreamReader:

This method involves creating an InputStreamReader object to read the input stream, and then reading the data character by character and appending it to a StringBuilder object. This approach is efficient and can handle different character encodings.

Sample code:

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

public class InputStreamToStringExample {

    public static void main(String[] args) throws IOException {
        // open an input stream to a file called "example.txt"
        InputStream inputStream = InputStreamToStringExample.class.getResourceAsStream("example.txt");

        // call the convertInputStreamToString() method and print the result
        String result = convertInputStreamToString(inputStream);
        System.out.println(result);
    }

    // define the convertInputStreamToString() method to convert the input stream to a string
    private static String convertInputStreamToString(InputStream inputStream) throws IOException {
        // create a new InputStreamReader object to read the input stream
        InputStreamReader isr = new InputStreamReader(inputStream);

        // create a new BufferedReader object to read the input stream efficiently
        BufferedReader br = new BufferedReader(isr);

        // create a new StringBuilder object to accumulate the data read from the input stream
        StringBuilder sb = new StringBuilder();

        // read the input stream character by character and append it to the StringBuilder
        int c;
        while ((c = br.read()) != -1) {
            sb.append((char) c);
        }

        // close the input stream and the BufferedReader
        br.close();
        isr.close();

        // return the resulting string
        return sb.toString();
    }
}

The output of the code will be the contents of the “example.txt” file, converted to a String:

Code Explanation:

  1. Start by importing the necessary classes and defining a public class called InputStreamToStringExample.
  2. Inside the InputStreamToStringExample class, we define a main() method that opens an input stream to a file called “example.txt” using the getResourceAsStream() method. This method is used to read resources that are stored in the same package as the class. You can replace this with any input stream that you want to convert to a string.
  3. We then call the convertInputStreamToString() method, passing in the input stream as a parameter, and print the resulting string to the console.
  4. The convertInputStreamToString() method is defined as a private static method that takes an InputStream as a parameter and returns a String.
  5. Inside the convertInputStreamToString() method, we create a new InputStreamReader called isr to read the input stream. This is done by passing the input stream to the constructor of the InputStreamReader.
  6. We also create a new BufferedReader called br to read the input stream efficiently. This is done by passing the isr object to the constructor of the BufferedReader.
  7. We then create a new StringBuilder called sb to accumulate the data read from the input stream.
  8. We use a while loop to read the input stream character by character and append each character to the StringBuilder sb. This is done by calling the read() method of the BufferedReader, which returns the next character in the input stream as an integer. We append this integer cast to a char to the StringBuilder.
  9. Once the input stream has been fully read and appended to the StringBuilder, we close the input stream and the BufferedReader to free up system resources.
  10. Finally, we return the resulting string by calling the toString() method of the StringBuilder.

Best of the four methods:

Using BufferedReader and StringBuilder to convert an InputStream to a String in Java is a highly efficient and reliable method.

There are several reasons why this approach is considered the best one.

  1. This method reads the input stream line by line, which is much more efficient than reading character by character or byte by byte. Moreover, it uses a StringBuilder to accumulate the data read from the stream, which is more memory-efficient than using a ByteArrayOutputStream.
  2. This method uses an InputStreamReader with a specified character encoding. This is crucial if the input stream contains non-ASCII characters or uses a different character encoding than the default. This allows the method to handle different character encodings and ensures that the resulting String is accurate and complete.
  3. While this method may require more code than some other methods, it is still easy to understand and implement. The code can be written in just a few lines, and the use of BufferedReader and StringBuilder are familiar to most Java developers.

Sample Problems for converting InputStream to string in java

Sample Problem 1:

Given an InputStream object containing the text file “sample.txt”, Write a Java program to read the contents of the file into a String and then count the frequency of each character in the String. Finally, print the character frequency counts as a table.

Solution:

  1. Create an InputStream object containing the text file “sample.txt”.
  2. Create a BufferedReader object to read the input stream.
  3. Create a StringBuilder object to accumulate the data read from the stream.
  4. Use the read() method of the BufferedReader object to read the characters from the input stream and append them to the StringBuilder object.
  5. Convert the StringBuilder object to a String using the toString() method.
  6. Create a HashMap object to store the character frequency counts.
  7. Loop through each character in the String and increment its count in the HashMap.
  8. Print the character frequency counts as a table.

Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class InputStreamToStringExample {

    public static void main(String[] args) throws IOException {
        // create an InputStream object containing the text file
        InputStream inputStream = InputStreamToStringExample.class.getResourceAsStream("sample.txt");

        // create a BufferedReader object to read the input stream
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        // create a StringBuilder object to accumulate the data read from the stream
        StringBuilder builder = new StringBuilder();

        // read the characters from the input stream and append them to the StringBuilder object
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        // convert the StringBuilder object to a String
        String text = builder.toString();

        // create a HashMap object to store the character frequency counts
        Map<Character, Integer> counts = new HashMap<>();

        // loop through each character in the String and increment its count in the HashMap
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            counts.put(c, counts.getOrDefault(c, 0) + 1);
        }

        // print the character frequency counts as a table
        for (Map.Entry<Character, Integer> entry : counts.entrySet()) {
            System.out.printf("| %8s | %8d |\n", entry.getKey(), entry.getValue());
        }
    }
}

Sample Problem 2:

You are given an input file containing a list of names separated by commas, write a Java program to read the contents of the file and store the names in an ArrayList. (Use the Scanner class)

Solution:

  1. Create a File object to represent the input file.
  2. Create a Scanner object to read from the file.
  3. Set the delimiter of the scanner to “,” to separate the names.
  4. Create an ArrayList to store the names.
  5. Loop through the scanner and add each name to the ArrayList.
  6. Close the scanner.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class NameListReader {
    public static void main(String[] args) {
        // Step 1: Create a File object for the input file
        File inputFile = new File("names.txt");

        try {
            // Step 2: Create a Scanner object to read from the input file
            Scanner scanner = new Scanner(inputFile);

            // Step 3: Set the delimiter of the scanner to ","
            scanner.useDelimiter(",");

            // Step 4: Create an ArrayList to store the names
            ArrayList<String> nameList = new ArrayList<>();

            // Step 5: Loop through the scanner and add each name to the ArrayList
            while (scanner.hasNext()) {
                String name = scanner.next().trim();
                nameList.add(name);
            }

            // Step 6: Close the scanner
            scanner.close();

            // Print the contents of the ArrayList
            System.out.println("Names read from file:");
            for (String name : nameList) {
                System.out.println(name);
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        }
    }
}

Sample Problem 3: 

You have a text file containing a short poem. Write a Java program to read the contents of the file using the ByteArrayOutputStream class and output the poem.

Solution:

  1. Create a File object for the input file.
  2. Create a FileInputStream object to read from the file.
  3. Create a ByteArrayOutputStream object to write the contents of the file.
  4. Create a buffer array to read the file contents into.
  5. Loop through the file, reading bytes into the buffer and writing them to the ByteArrayOutputStream.
  6. Close the input stream.
  7. Convert the resulting byte array to a string using the String constructor.
  8. Output the poem string.

Code:

import java.io.*;

public class PoemReader {
    public static void main(String[] args) {
        // Step 1: Create a File object for the input file
        File inputFile = new File("poem.txt");

        try {
            // Step 2: Create a FileInputStream object to read from the file
            FileInputStream inputStream = new FileInputStream(inputFile);

            // Step 3: Create a ByteArrayOutputStream object to write the contents of the file
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            // Step 4: Create a buffer array to read the file contents into
            byte[] buffer = new byte[1024];

            int length;
            // Step 5: Loop through the file, reading bytes into the buffer and writing them to the ByteArrayOutputStream
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }

            // Step 6: Close the input stream
            inputStream.close();

            // Step 7: Convert the resulting byte array to a string using the String constructor
            String poem = new String(outputStream.toByteArray());

            // Step 8: Output the poem string
            System.out.println(poem);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Sample Problem 4: 

You have an InputStream that contains some text data in the UTF-8 encoding. Write a Java program to convert the InputStream to a String using the InputStreamReader method.

Solution:

  1. Create an InputStream object that contains the text data to be read.
  2. Create an InputStreamReader object to read the characters from the InputStream. Pass the InputStream and the encoding (UTF-8) as arguments to the constructor.
  3. Create a StringBuilder object to store the characters read from the InputStreamReader.
  4. Read the characters from the InputStreamReader using the read() method. This method returns the integer value of the character read.
  5. Append the character to the StringBuilder object using the append() method.
  6. Repeat steps 4 and 5 until the read() method returns -1, which indicates the end of the InputStream.
  7. Convert the StringBuilder object to a String using the toString() method.

Code:

import java.io.*;

public class InputStreamToStringExample {
    public static void main(String[] args) {
        // Step 1: Create an InputStream object
        InputStream inputStream = new ByteArrayInputStream("Hello World!".getBytes());

        // Step 2: Create an InputStreamReader object
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");

        // Step 3: Create a StringBuilder object
        StringBuilder stringBuilder = new StringBuilder();

        try {
            int character;
            // Step 4: Read the characters from the InputStreamReader
            while ((character = inputStreamReader.read()) != -1) {
                // Step 5: Append the character to the StringBuilder object
                stringBuilder.append((char) character);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Step 7: Convert the StringBuilder object to a String
        String result = stringBuilder.toString();
        System.out.println(result); // Output: Hello World!
    }
}

Conclusion:

To summarize, knowing how to convert InputStream to String in Java is essential for developers. It may be required to ensure compatibility with certain APIs, to effectively handle and analyse text data, or for convenience. In this blog , we have found the answers to the question “How to convert InputStream to string in java” , we explored four methods for converting InputStream to String – BufferedReader and StringBuilder, Scanner, ByteArrayOutputStream, and InputStreamReader.

Each method has its own benefits and limitations, and developers must choose the most appropriate one for their particular scenario.

By using the sample code provided, Java developers can easily implement the conversion and enhance their code.