Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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 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.

Related questions

Browse Categories

...