Question:
How to convert String to InputStream in Java?
Code:
import java.io.*; public class StringToInputStream { public static void main(String[] args) throws IOException { String str = "Do you like green eggs and ham? I do not like them, Sam I am."; // Convert String into InputStream InputStream is = new ByteArrayInputStream(str.getBytes()); // Read it with BufferedReader InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); } }
Output:
$ java StringToInputStream Do you like green eggs and ham? I do not like them, Sam I am.