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 = "Programiz"; 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: Programiz 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()

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community