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

JavaStringType ConversionInputstream

Java Problem Overview


Given a string:

String exampleString = "example";

How do I convert it to an InputStream?

Java Solutions


Solution 1 - Java

Like this:

InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.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.

For versions of Java less than 7, replace StandardCharsets.UTF_8 with "UTF-8".

Solution 2 - Java

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

String source = "This is the source of my input stream";
InputStream in = org.apache.commons.io.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.

Solution 3 - Java

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

Solution 4 - Java

There are two ways we can convert String to InputStream in Java,

  1. Using ByteArrayInputStream

Example :-

String str = "String contents";
InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));

2) Using Apache Commons IO

Example:-

String str = "String contents"
InputStream is = IOUtils.toInputStream(str, StandardCharsets.UTF_8);

Solution 5 - Java

You can try cactoos for that.

final InputStream input = new InputStreamOf("example");

The object is created with new and not a static method for a reason.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIainView Question on Stackoverflow
Solution 1 - JavaIainView Answer on Stackoverflow
Solution 2 - JavaElijahView Answer on Stackoverflow
Solution 3 - JavaA_MView Answer on Stackoverflow
Solution 4 - JavaAnil NivargiView Answer on Stackoverflow
Solution 5 - JavaandreossView Answer on Stackoverflow