Convert a String to an InputStream in Java using Apache Commons IO

This code example shows how to convert a String to an InputStream using the Apache Commons IO library. Converting a String to an InputStream is sometimes necessary when for example we need to call some api that require a InputStream object as parameter but the value you need to pass is stored in a String object. To convert the parameter ‘name’ in the example below to an InputStream we simply use the IOUtils class which has a static method called ‘toInputStream’. The method takes the string we want to convert as parameter along with a character set and in the example we choose the common character set “UTF-8”.
Finally to make sure it has succeeded we print out every byte (character) in the stream on a separate row. Since the read-method of the inputstream returns an int, which is the decimal value of the byte, we convert the int value to a char before we print it out.

The output from the code above is: