inputstream from/to string

Fast way I can think of is using the apache common api:

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

Copy method can either use Charset.forName(“UTF-8”) or take String “UTF-8” directly.

Or Even easier:

String myString = IOUtils.toString(myInputStream, "UTF-8");

 

 

Opposite:

public class StringToStream {

    public static void main(String[] args) {
        String text = "Converting String to InputStream Example";
        
        /*
         * Convert String to InputStream using ByteArrayInputStream
         * class. This class constructor takes the string byte array
         * which can be done by calling the getBytes() method.
         */
        try {
            InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s