How to Convert InputStream to Byte Array in Java? - GeeksforGeeks

31 Jul, 2021
In Java, input stream refers to an ordered flow of data in the form of bytes. This flow of data can be coming from various resources such as files, network programs, input devices, etc. In order to read such data, we have a Java InputStream Class in the Java IO API. There are several methods to convert this input stream into a byte array (or byte[]) which can be used as and when required. We’ll now have a look at some methods to do the same which are listed as follows:
Methods:
Using read(byte[]) or readAllBytes()Using ByteArrayOutputStream ClassUsing ByteStreams utility classUsing Apache Commons IO Library
Using read(byte[]) or readAllBytes()
Using ByteArrayOutputStream Class
Using ByteStreams utility class
Using Apache Commons IO Library
Now we will be discussing each and every method to detail in order and understanding the implementation the same via clean java programs as follows:
Method 1: Using read(byte[]) or readAllBytes()
In the InputStream class, we have a read() method where a byte array can be passed as a parameter to get the input stream data in the form of a byte array. But this method has a shortcoming that it can read the data at most the size of the array passed as a parameter. It works well only if we know the size of incoming data beforehand. The method returns an int value equal to the number of bytes read into the array or -1 if the stream end is reached.
Syntax: 
Declaration read(byte[])
public int read​(byte[] byteArray)
throws IOException
To overcome the drawback of having to know the input size beforehand, we have another method called readAllBytes() since Java 9. This method can read all bytes available in the input stream. The method is way more faster and efficient in converting input stream to a byte array.
Syntax: readAllBytes()
public byte[] readAllBytes()
throws IOException
Example
Java
// Java Program to Convert InputStream to Byte Array// Using read(byte[]) or readAllBytes()  // Importing required classesimport java.io.*;import java.nio.charset.StandardCharsets;  // Main classclass GFG {      // Main driver method    public static void main(String[] args)    {        // Creating a Input Stream here        // Usually it comes from files, programs        InputStream inputStream = new ByteArrayInputStream(            "GeeksForGeeks".getBytes(                StandardCharsets.UTF_8));          // Taking the InputStream data into a byte array        byte[] byteArray = null;          // Try block to check for exceptions        try {            byteArray = inputStream.readAllBytes();        }          // Catch block to handle the exceptions        catch (IOException e) {              // Print and dispal ythe exceptions            System.out.println(e);        }          // Iterating over using for each loop        for (byte b : byteArray)              // Printing the content of byte array            System.out.print((char)b + " ");    }}
G e e k s F o r G e e k s 
Example 2: Using ByteArrayOutputStream Class
This is an indirect method of conversion of input stream data into a byte array. Here we will be using an object of ByteArrayOutputStream class as a buffer. For this, we read each byte from a InputStream class and write it to a ByteArrayOutputStreamclass. Later we call toByteArray() that returns the output stream in the form of a byte array.
Example 
Java
// Java Program to Convert InputStream to Byte Array// Using ByteArrayOutputStream Class  // Importing required classesimport java.io.*;import java.nio.charset.StandardCharsets;  // Main classclass GFG {      // Main driver method    public static void main(String[] args)    {        // Creating a Input Stream here (usually it comes        // from files, programs, etc.)        InputStream inputStream = new ByteArrayInputStream(            "GeeksForGeeks".getBytes(                StandardCharsets.UTF_8));          // Taking the InputStream data into a byte array        // output stream          // Buffer size taken to be 1000 say.        byte[] buffer = new byte[1000];          // Creating an object of ByteArrayOutputStream class        ByteArrayOutputStream byteArrayOutputStream            = new ByteArrayOutputStream();          // Try block to check for exceptions        try {            int temp;              while ((temp = inputStream.read(buffer))                   != -1) {                byteArrayOutputStream.write(buffer, 0,                                            temp);            }        }          // Catch block to handle the exceptions        catch (IOException e) {              // Display the exception/s on the console            System.out.println(e);        }          // Mow converting byte array output stream to byte        // array        byte[] byteArray            = byteArrayOutputStream.toByteArray();          // Iterating over using for each loop        for (byte b : byteArray)              // Printing the content of byte array            System.out.print((char)b + " ");    }}
G e e k s F o r G e e k s 
Method 3: Using ByteStreams utility class
ByteStreams utility class from the Guava Library has a direct method to convert input stream to a byte array.
Google Guava is an open-source(a decentralized software-development model that encourages open collaboration) set of common libraries for Java, mainly developed by Google engineers. It helps in reducing coding errors. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations.
Example
Java
// Java Program to Convert InputStream to Byte Array// Using ByteArrayOutputStream Class  // Importing required classes, here additionally// We are importing from Guava Libraryimport com.google.common.io.ByteStreams;import java.io.*;import java.nio.charset.StandardCharsets;  // Main classclass GFG {      // Main driver method    public static void main(String[] args)    {        // Creating a Input Stream here        // usually it comes from files, programs        InputStream inputStream = new ByteArrayInputStream(            "GeeksForGeeks".getBytes(                StandardCharsets.UTF_8));          // Taking the InputStream data into a byte array        // using ByteStreams        byte[] byteArray = null;          // Try block to check for exceptions        try {            byteArray                = ByteStreams.toByteArray(inputStream);        }          // Catch block to handle the exceptions        catch (IOException e) {              // Display the exceptions on the console window            System.out.println(e);        }          // Iterating over using for each loop        for (byte b : byteArray)              // Printing the content of byte array            System.out.print((char)b + " ");    }}
Method 4: Using Apache Commons IO Library
This method is very similar to using ByteStreams class. Here we make use of IOUtils class which has a similar method with the same name toByteArray() that returns the inputstream data as a byte array. The usage same we just need to use import org.apache.commons.io.IOUtils rather that ByteStreams of Guava Library.
Syntax: 
byte[] byteArray = IOUtils.toByteArray(inputStream); 
Note: However, this method often needs the addition of dependency to the editor.
Java-Array-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?