In this tutorial, we will learn how to Convert String to InputStream in Java.
While working on Strings, sometimes we come across big String that we want to process it incrementally or a small portion of it at a time. Then in this scenario, converting String to InputStream will be useful.
InputStream is an abstract class representing an input stream of bytes. It implements the Closeable interface. This abstract class is the super class of all classes. Most of the methods in this class will throw an IOException on error conditions.
Let’s see how to Convert String to InputStream with an example.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package net.javaforyou.collections; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class ConvertStringToInputStream { public static void main(String[] args) throws IOException { String str = "This is a String to InputStream conversion demo."; // convert String into InputStream InputStream inputStream = new ByteArrayInputStream(str.getBytes()); // Read inputStream using BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); } } |
Output:
1 |
This is a String to InputStream conversion demo. |
In the above program, we have converted String to InputStream.
Other tutorials: