Java Program to Convert a String into the InputStream

To understand this example, you should have the knowledge of the following Java programming topics:


Example: Java Program to convert String to InputStream

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class Main {

  public static void main(String args[]) {

    // Creates a string
    String name = "codemy";
    System.out.println("String is: " + 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
      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();
    }
  }
}

Output

String is: codemy
InputStream: java.io.ByteArrayInputStream@5479e3f
Available bytes at the beginning: 9
Available bytes at the end: 6

In the above example, we have created a string named name. Here, we have are converting the string into the input stream named stream.

The getBytes() method converts the string into bytes. To learn more, visit Java String getBytes()