Today we will look into how to convert String to InputStream in java. Recently I wrote a post to convert InputStream to String.
Java String to InputStream
There are two ways that I have used to convert String to InputStream.
- Java IO ByteArrayInputStream class
- Apache Commons IO IOUtils class
Let’s have a look at example program to use these classes.
Java String to InputStream using ByteArrayInputStream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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 StringToInputStreamUsingByteArrayInputStream { public static void main(String[] args) throws IOException { String str = "convert String to Input Stream Example using ByteArrayInputStream"; // convert using ByteArrayInputStream InputStream is = new ByteArrayInputStream(str.getBytes(Charset.forName("UTF-8"))); // print it to console BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = br.readLine(); while (line != null) { System.out.println(line); line = br.readLine(); } } } |
String to InputStream using Apache Commons IOUtils
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import org.apache.commons.io.IOUtils; public class StringToInputStreamUsingIOUtils { public static void main(String[] args) throws IOException { String str = "Example using Apache Commons IO class IOUtils"; InputStream stream = IOUtils.toInputStream(str, Charset.forName("UTF-8")); stream.close(); } } |
You can use IOUtils
if you are already using Apache Commons IO jars, otherwise there is no benefit since internally it’s using ByteArrayInputStream class. Below is the toInputStream
method implementation from IOUtils
class source code.
1 2 3 4 5 |
public static InputStream toInputStream(final String input, final Charset encoding) { return new ByteArrayInputStream(input.getBytes(Charsets.toCharset(encoding))); } |
That’s all about converting String to Input Stream in java.