English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to convert an input stream to a byte array in Java.
To understand this example, you should be familiar with the followingJava ProgrammingTopic:
import java.io.InputStream; import java.util.Arrays; import java.io.ByteArrayInputStream; public class Main { public static void main(String args[]) { try { //Create input stream byte[] input = {1, 2, 3, 4}; InputStream stream = new ByteArrayInputStream(input); System.out.println("Input Stream: " + stream); //Convert the input stream to a byte array byte[] array = stream.readAllBytes(); System.out.println("Byte array: " + Arrays.toString(array)); stream.close(); } catch (Exception e) { e.getStackTrace(); } } }
Output Result
Input Stream: java.io.ByteArrayInputStream@27082746 Byte array: [1, 2, 3, 4]
In the above example, we created an input stream named stream (InputStream). Note this line,
byte[] array = stream.readAllBytes();
Here, the readAllBytes() method returns all data from the stream and stores it in a byte array.
Note: We have used the Arrays.toString() method to convert the entire array to a string.
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 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 the input stream byte[] array = new byte[4]; int i; //Read all data from the input stream to the array while ((i = stream.read(array, 0, array.length)) != -1) { //Write all data in the array to the output output.write(array, 0, i); } byte[] data = output.toByteArray(); //Convert the input stream to a byte array System.out.println("Byte Array: ") + Arrays.toString(data)); stream.close(); } catch (Exception e) { e.getStackTrace(); } } }
Output Result
Input Stream: java.io.ByteArrayInputStream@27082746 Byte Array: [1, 2, 3, 4]
In the above example, we create an input stream input from the array. Note the expression
stream.read(array, 0, array.length)
Here, all elements in the stream are stored in an array, starting from index 0. Then, we store all elements of the array into 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 to a byte array named data.