In this tutorial, we are going to learn how to convert an InputStream to a byte array using plain Java and external libraries like Guava or Apache Commons IO. In many cases, there is a need to use byte[] instead of Strings mainly because processing arrays is fast and not resource consuming.
For more Java I/O related articles, check the following links:
2. Convert InputStream to byte array using ByteArrayOutputStream
Natural way to convert an InputStream to byte array is to use plan Java solution based on ByteArrayOutputStream:
In this example, we created ByteArrayOutputStream and write to it blocks of read data from the InputStream. Then, we used the toByteArray() method to get wanted byte array.
BTW. we use example list of bytes that represent our domain name:
3. InputStream to byte[] using ByteArrayInputStream
When we have the opportunity to use ByteArrayInputStream, instead of any other different InputStream, this will be the best way to get byte array out stream. This is because ByteArrayInputStream contains method read that takes byte[
4. Conversion from InputStream to a byte array using Guava
To convert InputStream to byte[] we can also use external libraries like Guava. The Guava based solution using ByteStreams utility class looks like the following:
To start working with Guava we should include special dependency to our project:
The latest version of Guava library is available here:
Apache Commons IO comes with similar to Guava solution to convert an InputStream to a byte array:
Of course, first we need to include Apache Commons IO dependency to our project or download JAR. The following presents the way we could include library in POM.xml file:
This article presented several ways to convert an InputStream to byte array in Java using built-in methods from Java IO and using libraries like: Guava or Apache Commons IO.
The examples illustrated in this tutorial can be found in our GitHub project.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}