0 votes
1 view
in Java by (4.1k points)

Given a string:

String exampleString = "example";

How do I convert it to an InputStream?

1 Answer

0 votes
by (46.1k 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(); } } }


xyz. qty

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

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !