Convert a String into InputStream in Java

Exercise:

Write a Java Program to convert a string into the input stream.

Click Here to View the Solution!
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class StringToIS {
    public static void main(String args[]) {
        String name = "CodeOfCode";
        System.out.println("String = " + name);
        try {
            InputStream stream = new ByteArrayInputStream(name.getBytes(StandardCharsets.UTF_8));
            System.out.println("InputStream: " + stream);
           
            // Returns the available number of bytes
            System.out.println("Available bytes at the beginning= " + stream.available());
           
            // Reads 3 bytes from the stream
            stream.read();
            stream.read();
            stream.read();
           
            // After reading 3 bytes returns the available number of bytes
            System.out.println("Available bytes at the end= " + stream.available());
            stream.close();
        }
        catch (Exception e) {
            e.getStackTrace();
        }
    }
}
Click Here to View the Output!
 String = CodeOfCode
 InputStream: java.io.ByteArrayInputStream@5b1d2887
 Available bytes at the beginning= 10
 Available bytes at the end= 7
Click Here to View the Explanation!
  • In this program, first a string called name is initialized.
  • This string is then printed on the screen.
  • Next, in a try block, an input stream is created which basically converts the variable name into an input stream called stream. This is done through the getBytes() method.
  • An input string is transformed into byte form by getBytes() method.
  • The input stream is then displayed on the screen.
  • The number of bytes available in the stream are checked through the available() method and printed on the screen as the bytes available in the beginning.
  • Then the read method is called thrice i.e. three bytes are read from the stream.
  • Afterwards, the available method is applied again to check the bytes at the end which are then printed to the screen.
  • Then the stream is closed.
  • In the catch block, exception is handled.