This post will discuss how to convert InputStream to byte array in Java.

1. Using java.io.ByteArrayOutputStream

The idea is to read each byte from the specified InputStream and write it to a ByteArrayOutputStream, then call toByteArray() to get the current contents of this output stream as a byte array. Since the total number of bytes to be read is unknown, we have allocated the buffer of size 1024.

Download  Run Code

Output:

Techie Delight

2. Using Guava Library

We can use ByteStreams class from Guava, whose toByteArray() method reads all bytes from an input stream into a byte array.

Download Code

Output:

Techie Delight

3. Using Apache Commons IO

Like Guava, Apache Commons IO has IOUtils class whose toByteArray() method returns the contents of an InputStream as a byte array.

Download Code

Output:

Techie Delight

4. Using sun.misc.IOUtils

We can also use sun.misc.IOUtils, which is one of Sun’s proprietary Java classes. We should avoid their use as it is not guaranteed to work on all Java-compatible platforms or even in future versions on the same platform.

Download Code

Output:

Techie Delight

5. Using Java 9

In Java 9, we can do something like:

 
Or use ByteArrayOutputStream.transferTo() method:

That’s all about converting InputStream to byte array in Java.