Convert a String to an Input Stream in Java

In this post, we will discuss how to convert the specified string to an input stream in Java, encoded as bytes using the specified character encoding.


1. ByteArrayInputStream

The idea is to get sequence of bytes from the given specified and create a ByteArrayInputStream from it as shown below. This works as ByteArrayInputStream class extends the InputStream class. We have used StandardCharsets.UTF_8 to specify the charset. Before Java 7, we can use Charset.forName("UTF-8").


Download   Run Code


2. Using Apache Commons IO

Apache Commons IO IOUtils class provides several IO stream manipulation utility static methods. One such method is toInputStream() which converts the specified string to an input stream using the specified character encoding.



1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of