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: