InputStreamString
How to convert String to InputStream in Java
In the previous tutorial, we discussed how can we convert an InputStream
into a String
. In this tutorial we are going to see the opposite direction. So, we are going to covert a String
into an InputStream
.
When you have a very big String
that you want to process it incrementally, or a small portion of it at a time, converting it to an InputStream
can be very helpful. In the previous tutorials what we actually did was to read the bytes from an input stream and append them to a String
variable. In this tutorial we’re going to do the same technique.
Basically we are going to :
- Get the bytes of the String
- Create a new
ByteArrayInputStream
using the bytes of theString
- Assign the
ByteArrayInputStream
object to anInputStream
variable (which you can do asInputStream
is a superclass ofByteArrayInputStream
)
Here is the code:
package com.javacodegeeks.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 = "This is a String.\nWe are going to convert it to InputStream.\n" + "Greetings from JavaCodeGeeks!"; //use ByteArrayInputStream to get 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:
This is a String. We are going to convert it to InputStream. Greetings from JavaCodeGeeks!
This was an example of how to convert String to InputStream in Java.
InputStream inputStream = new ReaderInputStream(new StringReader(string))