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

1. Using ByteArrayInputStream

The idea is to get a 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 the 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 Code

That’s all about converting a String to an Input Stream in Java.