This question already has an answer here:
I'm not used to working with streams in Java - how do I create an InputStream
from a String
?
This question already has an answer here:
I'm not used to working with streams in Java - how do I create an InputStream
from a String
?
You could do this:
Note the
UTF-8
encoding. You should specify the character set that you want the bytes encoded into. It's common to chooseUTF-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:Here you go:
Update For multi-byte support use (thanks to Aaron Waibel's comment):
Please see ByteArrayInputStream manual.
It is safe to use a charset argument in String#getBytes(charset) method above.
After JDK 7+ you can use
instead of hardcoded encoding string:
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:
Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.
Java 7+
It's possible to take advantage of the
StandardCharsets
JDK class:Beginning with Java 7, you can use the following idiom: