Java IO Java String Handling

Java String to InputStream example

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

How to convert String to InputStream in Java?

Convert String to byte array first using toBytes method of String class. Once you get the byte array, use ByteArrayInputStream class to convert String to InputStream.

Example

Output

It is always advisable to mention the character set while converting String to 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 below example.

Output

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

Convert String to InputStream using Apache Commons library

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

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

Example

Output

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

Join 1000+ fellow learners! Enter your email address below: