How to create an InputStream from a String in Java?

August 22, 2017

This short post will present how to convert String to InputStream in Java.

1. The String.getBytes() method with ByteArrayInputStream constructor

At the beginning, we declared a String and used the String.getBytes() method to convert it to the bytes array. We created a new InputStream object by using the constructor of the ByteArrayInputStream class, passing the bytes array as a method constructor parameter.

2. Apache Commons

If you are familiar with Apache libraries, you can make use of IOUtils class:

The output will be the same as before.



Click here to add a comment

Leave a comment: