English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input/Output (I/O)/O)

Java Reader/Writer

Java Other Topics

Java program converts string to InputStream

Comprehensive Java Examples

In this program, we will learn how to convert a string to an InputStream in Java.

To understand this example, you should be familiar with the followingJava ProgrammingTopic:

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[]) {
    //Create a string
    String name = "w3codebox";
    System.out.println("The string is: ") + name);
    try {
      InputStream stream = new ByteArrayInputStream(name.getBytes(StandardCharsets.UTF_)8));
      System.out.println("InputStream: ") + stream);
      //Return the number of available bytes
      System.out.println("Available bytes start: ") + stream.available());
      //Read from the stream stream3bytes
      stream.read();
      stream.read();
      stream.read();
      //read3bytes later
      //Return the number of available bytes
      System.out.println("Last available byte: ", + stream.available());
      stream.close();
    }
    catch (Exception e) {
      e.getStackTrace();
    }
  }
}

Output Result

The string is: w3codebox
InputStream: java.io.ByteArrayInputStream@5479e3f
Starting available byte: 5
Last available byte: 2

In the above example, we created a string named name. Here, we convert the string to an input stream named stream.

The getBytes() method converts a string to bytes. For more information, please visitJava String getBytes()

Comprehensive Java Examples