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.

 

Download

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of