1. Introduction
In this article, we are going to learn how to convert byte array to InputStream in Java using built-in methods and external libraries like Guava
and Apache Commons IO
.
For more Java I/O related articles, check the following links:
2. Byte array to InputStream with ByteArrayInputStream
Let's start with a simple solution that comes with plain Java:
In this example we use ByteArrayInputStream
object to create an instance of the InputStream
type.
3. Convert byte array to InputStream using Guava
When using Guava
library, first we have to wrap byte array with ByteSource
object that contains openStream()
method which returns InputStream
:
4. Using Apache Commons IO
to convert byte[]
to InputStream
Apache Commons IO
library also gives us a solution but not so straightforward:
First, we have to create a String
object from our byte array, then use IOUtils.toInputStream
to convert it into InputStream
. Note that converting from String
to InputStream
requires encoding.
5. Conclusion
In this short article, we showed ways to convert byte array to InputStream in Java. We presented several solutions but suggest using the simplest one with the plain Java. This one is a straightforward way to achieve that conversion.
Code examples used in this tutorial can be found under our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}