Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (4k points)

Given a string:

String exampleString = "example";

How do I convert it to an InputStream?

1 Answer

0 votes
by (46k points)

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; import; import; import; import; import; 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(); } } }


xyz. qty

This was an example of how to convert String to InputStream in Java.

Related questions

Browse Categories