Home | FAQ | Contact me

Converting String to InputStream

It's sometimes useful to convert a String to a stream for use with various interfaces, StringBufferInputStream having long been deprecated. This example does assume something about the string being UTF-8. A real string, whose origin you don't know, might not be UTF-8.

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

public class StringToStream
{
    public static void main( String[] args )
    {
        String string = "Example of converting a String to an InputStream";

        try
        {
            InputStream is = new ByteArrayInputStream( string.getBytes( "UTF-8" ) );
        }
        catch( UnsupportedEncodingException e )
        {
            e.printStackTrace();
        }
    }
}