Converting String to InputStream in Java.
This example code shows how to convert a String to an InputStream object in Java using ByteArrayInputStream.
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 |
import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class StringToInputStreamExample { public static void main(String[] args) throws IOException { String str = "This is a String ~ GoGoGo"; // convert String into InputStream InputStream is = new ByteArrayInputStream(str.getBytes()); // read it with BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); } } |