1. Introduction
In this tutorial we are going to look at how to convert String to InputStream in Java. We will present solutions in plain Java and will use external libraries like Guava
and Apache Commons IO
.
For more Java I/O related articles, check the following links:
2. Convert String to InputStream using ByteArrayInputStream
The solution in plain Java is almost straightforward and, which is also important, we can achieve a wanted result without additional dependencies.
The following example shows how to use ByteArrayInputStream
to convert String to InputStream:
In this example first, we get bytes representing the String encoded using UTF-8
charset. Then, we create ByteArrayInputStream
instance that takes byte array as a constructor parameter.
Note that we should always provide the encoding of the given string unless the encoding matches the default platform charset.
3. Using Guava
to convert String to InputStream
With Guava
we can also achieve conversions from String to InputStream, however, the solution is more complex:
First, we are creating Reader
object using CharSource.wrap(str).openStream()
method. Then, we used ReaderInputStream
to convert Reader
to the InputStream
.
Note that using ReaderInputStream
constructor without a charset as a second parameter (charset) is deprecated now.
4. Converting String to InputStream using IOUtils
from Apache Commons IO
Using IOUtils
class from Apache Commons IO
gives us a pretty straightforward solution:
Here we have dedicated method IOUtils.toInputStream
that do the conversion transparently.
Note that using IOUtils.toInputStream(str)
with a single parameter is deprecated. Now we need to explicitly specify the encoding of the String as a second parameter.
5. Conclusion
In this article, we illustrated several methods to convert String to InputStream in Java. The important knowledge to remember is when we convert String to the byte stream we should always provide the encoding.
If you are looking for reverse method, that converts InputStream to a String check the following: InputStream -> String
As usual, code use in this article is available under our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}