How does one create an InputStream from a String?

JavaStringStream

Java Problem Overview


I'm not used to working with streams in Java - how do I create an InputStream from a String?

Java Solutions


Solution 1 - Java

Here you go:

InputStream is = new ByteArrayInputStream( myString.getBytes() );

Update For multi-byte support use (thanks to Aaron Waibel's comment):

InputStream is = new ByteArrayInputStream(Charset.forName("UTF-16").encode(myString).array());

Please see ByteArrayInputStream manual.

It is safe to use a charset argument in String#getBytes(charset) method above.

After JDK 7+ you can use

java.nio.charset.StandardCharsets.UTF_16

instead of hardcoded encoding string:

InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(myString).array());

Solution 2 - Java

You could do this:

InputStream in = new ByteArrayInputStream(string.getBytes("UTF-8"));

Note the UTF-8 encoding. You should specify the character set that you want the bytes encoded into. It's common to choose UTF-8 if you don't specifically need anything else. Otherwise if you select nothing you'll get the default encoding that can vary between systems. From the JavaDoc:

> The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.

Solution 3 - Java

InputStream in = new ByteArrayInputStream(yourstring.getBytes());

Solution 4 - Java

Java 7+

It's possible to take advantage of the StandardCharsets JDK class:

String str=...
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(str).array());

Solution 5 - Java

Beginning with Java 7, you can use the following idiom:

String someString = "...";
InputStream is = new ByteArrayInputStream( someString.getBytes(StandardCharsets.UTF_8) );
    

Solution 6 - Java

Instead of CharSet.forName, using com.google.common.base.Charsets from Google's Guava (http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets) is is slightly nicer:

InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );

Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmir RachumView Question on Stackoverflow
Solution 1 - JavaanubhavaView Answer on Stackoverflow
Solution 2 - JavaWhiteFang34View Answer on Stackoverflow
Solution 3 - Javauser235064View Answer on Stackoverflow
Solution 4 - JavaStephanView Answer on Stackoverflow
Solution 5 - JavaAbdullView Answer on Stackoverflow
Solution 6 - JavavorburgerView Answer on Stackoverflow