Example 1: Java Program to Convert InputStream to Byte Array
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
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.