Java Program to Convert the InputStream into Byte Array

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java Program to Convert InputStream to Byte Array

import java.io.InputStream;
import java.util.Arrays;
import java.io.ByteArrayInputStream;


public class Main {

  public static void main(String args[]) {

    try {

      // create an input stream
      byte[] input = {1, 2, 3, 4};
      InputStream stream = new ByteArrayInputStream(input);
      System.out.println("Input Stream: " + stream);

      // convert the input stream to byte array
      byte[] array = stream.readAllBytes();
      System.out.println("Byte Array: " + Arrays.toString(array));

      stream.close();
    }

    catch (Exception e) {
      e.getStackTrace();
    }
  }
}

Output

Input Stream: java.io.ByteArrayInputStream@27082746
Byte Array: [1, 2, 3, 4]

In the above example, we have created an input stream named stream. Note the line,

byte[] array = stream.readAllBytes();

Here, the readAllBytes() method returns all the data from the stream and stores in the byte array.

Note: We have used the Arrays.toString() method to convert all the entire array into a string.


Example 2: Convert InputStream to Byte Array using Output Stream

import java.io.InputStream;
import java.util.Arrays;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;


public class Main {

  public static void main(String args[]) {

    try {

      // create an input stream
      byte[] input = {1, 2, 3, 4};
      InputStream stream = new ByteArrayInputStream(input);
      System.out.println("Input Stream: " + stream);

      // create an output stream
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      // create a byte array to store input stream
      byte[] array = new byte[4];
      int i;

      // read all data from input stream to array
      while ((i = stream.read(array, 0, array.length)) != -1) {

        // write all data from array to output
        output.write(array, 0, i);
      }

      byte[] data = output.toByteArray();

      // convert the input stream to byte array
      System.out.println("Byte Array: " + Arrays.toString(data));
      stream.close();
    }

    catch (Exception e) {
      e.getStackTrace();
    }
  }
}

Output

Input Stream: java.io.ByteArrayInputStream@27082746
Byte Array: [1, 2, 3, 4]

In the above example, we have created an input stream from the array input. Notice the expression,

stream.read(array, 0, array.length)

Here, all elements from stream are stored in array, starting from index 0. We then store all elements of array to the output stream named output.

output.write(array, 0, i)

Finally, we call the toByteArray() method of the ByteArrayOutputStream class, to convert the output stream into a byte array named data.

Did you find this article helpful?