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