Write a Java Program to Convert a String into the InputStream

In Java, you can convert a string into an InputStream by using the ByteArrayInputStream class.

This class is available in the java.io package and allows you to read a byte array as a stream.


To convert a string into an InputStream, you first need to convert the string into a byte array.

You can do this by calling the getBytes() method on the string object.

This method returns a byte array that represents the string.

Once you have the byte array, you can create an instance of the ByteArrayInputStream class by passing the byte array as a parameter to its constructor.

This will create an InputStream object that you can use to read the contents of the byte array as a stream.

Here is an example Java program that demonstrates how to convert a string into an InputStream:

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

public class StringToInputStream {
    public static void main(String[] args) {
        String str = "Hello, world!";
        byte[] bytes = str.getBytes();
        InputStream inputStream = new ByteArrayInputStream(bytes);
        
        // Read from the input stream
        int data;
        try {
            while ((data = inputStream.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this example, we first create a string “Hello, world!”.

We then convert this string into a byte array by calling the getBytes() method on the string object.

Next, we create an instance of the ByteArrayInputStream class by passing the byte array as a parameter to its constructor.

This creates an InputStream object that we can use to read the contents of the byte array as a stream.

We then use a while loop to read from the input stream and print the data to the console.

The read() method of the InputStream class returns an integer that represents the next byte of data from the stream.

We cast this integer to a char and print it to the console.

Finally, we catch any exceptions that may be thrown during the reading process and print their stack trace to the console.


In conclusion, converting a string into an InputStream in Java is a simple process that involves converting the string into a byte array and creating an instance of the ByteArrayInputStream class with the byte array as a parameter.

This allows you to read the contents of the string as a stream.