How can I get a java.io.InputStream from a java.lang.String?

I have a String that I want to use as an InputStream. In Java 1.0, you could use java.io.StringBufferInputStream, 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 class.

You can create a java.io.Reader with java.io.StringReader, 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 java.io.ByteArrayInputStream:

public InputStream createInputStream(String s, String charset)
    throws java.io.UnsupportedEncodingException {

    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.


Solution 1:

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"))

Solution 2:

If you don't mind a dependency on the commons-io package, then you could use the IOUtils.toInputStream(String text) method.