Convert the InputStream into Byte Array in Java

Exercise:

Write a Java Program to convert the inputStream into byte array.

Click Here to View the Solution!
import java.io.InputStream;
import java.util.Arrays;
import java.io.ByteArrayInputStream;

public class IStoByteArray {
    public static void main(String args[]) {
        try {
            
            // create an input stream
            byte[] input = {'a','b','c','d'};
            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();
        }
    }
}
Click Here to View the Output!
 Input Stream = java.io.ByteArrayInputStream@27082746
 Byte Array: [97, 98, 99, 100]
Click Here to View the Explanation!
  • In this program, firstly a byte array named input has been created.
  • This array is then converted into an input stream named stream.
  • The input stream is then displayed on the screen.
  • Next, all the bytes from the input stream are read and stored in a byte type array named as array.
  • This newly created array is then printed to the screen using the Array class method called toString() which converts array contents into a string.
  • Then the stream is closed.

%d bloggers like this: