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

Jared Oberhaus picture Jared Oberhaus · May 8, 2009 · Viewed 82.5k times · Source

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.

Answer

Andres Riofrio picture Andres Riofrio · Jan 3, 2013

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