Home » Java » How do I convert a String to an InputStream in Java? [duplicate]

How do I convert a String to an InputStream in Java? [duplicate]

Posted by: admin November 2, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

Like this:

InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8.name()));

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

For versions of Java less than 7, use "UTF-8" instead.

Questions:
Answers:

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, "UTF-8");

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.

Questions:
Answers:

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