views:

618

answers:

3

Given a string:

String exampleString = "example";

How do I convert this to an InputStream?

+20  A: 

Like this:

InputStream stream = new ByteArrayInputStream(exampleString.getBytes("UTF-8"));

Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as UTF-8.

Iain
+6  A: 

You could use a StringReader and convert the reader to an input stream using the solution in this other stackoverflow post.

A_M
+3  A: 

I find that using Apache Commons IO makes my life much easier.

String source = "This is the source of my input stream";
InputStream in = IOUtils.toInputStream(source);

You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.

Elijah