Friday, 10 August 2012

How to Convert an InputStream into a Byte Array in Java?

Sometimes, one has an input stream and would like to retrieve the content in a byte array. Unfortunately, Java does not deliver a suitable method for this. Fortunately, the Apache Commons library provides a solution:
byte[] ba = { -1, 2, -3, 4, 0, 66 };
InputStream bais = new ByteArrayInputStream(ba);

byte[] retr = IOUtils.toByteArray(bais);

System.out.println("Expected  : " + Arrays.toString(ba));
System.out.println("Retrieved : " + Arrays.toString(retr));
The generated output is:
Expected  : -1 2 -3 4 0 66 
Retrieved : -1 2 -3 4 0 66
This code example is also available from Github, in the Java-Core-Examples directory.

More Java tips & tricks here.

No comments:

Post a Comment