Java – How to get a from a java.lang.String


I have a String that I want to use as an InputStream. In Java 1.0, you could use, but that has been @Deprecrated (with good reason–you cannot specify the character set encoding):

This class does not properly convert
characters into bytes. As of JDK 1.1,
the preferred way to create a stream
from a string is via the StringReader

You can create a with, but there are no adapters to take a Reader and create an InputStream.

I found an ancient bug asking for a suitable replacement, but no such thing exists–as far as I can tell.

The oft-suggested workaround is to use java.lang.String.getBytes() as input to

public InputStream createInputStream(String s, String charset)
    throws {

    return new ByteArrayInputStream(s.getBytes(charset));

but that means materializing the entire String in memory as an array of bytes, and defeats the purpose of a stream. In most cases this is not a big deal, but I was looking for something that would preserve the intent of a stream–that as little of the data as possible is (re)materialized in memory.

Best Solution

Update: This answer is precisely what the OP doesn't want. Please read the other answers.

For those cases when we don't care about the data being re-materialized in memory, please use:

new ByteArrayInputStream(str.getBytes("UTF-8"))