we are going to :
- Get the bytes of the String
- Create a new ByteArrayInputStream using the bytes of the String
- Assign the ByteArrayInputStream object to an InputStream variable (which you can do as InputStream is a superclass of ByteArrayInputStream)
Here is the code:
package com.xyz.java.core; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; public class StringToInputStream { public static void main(String[] args) throws IOException { String string = "xyz .\n" + "qty"; //apply ByteArrayInputStream to receive the bytes of the String and convert them to InputStream. InputStream inputStream = new ByteArrayInputStream(string.getBytes(Charset.forName("UTF-8"))); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String output = bufferedReader.readLine(); while (output != null) { System.out.println(output); output = bufferedReader.readLine(); } } }
Output:
xyz. qty
This was an example of how to convert String to InputStream in Java.