Skip to content

Java String to InputStream example

Java String to InputStream example shows how to convert String to InputStream in Java. The example also shows how to set character encoding while converting String.

How to convert String to InputStream in Java?

First, convert String to a byte array using the toBytes method of the String class. Once we get the byte array, use the ByteArrayInputStream class to convert it to the String.

Example

Output

It is always advisable to mention the character set while converting the String to a byte array using getBytes method. If the default character set of the platform you are using is ASCII, and if the String is encoded in UTF-8 encoding, characters will be lost during the conversion as given in the below example.

Output

As you can see from the output, the missing characters are displayed as question marks.

Convert String to InputStream using the Apache Commons library

If you are using the Apache Commons library, you can use the toInputStream method of IOUtils class to convert the String.

This method converts the specified String to InputStream with bytes encoded using a specified encoding.

Example

Output

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.