My background is .net, I'm fairly new to Java. I'm doing some work for our company's java team and the architect needs me to implement a method that takes an InputStream (java.io) object. In order to fulfill the method's purpose I need to convert that into a byte array. Is there an easy way to do this?
Asked
Active
Viewed 5.2k times
20
-
Be aware that this may be memory hogging. – BalusC Jan 29 '10 at 17:18
2 Answers
61
The simplest way is to create a new ByteArrayOutputStream
, copy the bytes to that, and then call toByteArray
:
public static byte[] readFully(InputStream input) throws IOException
{
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = input.read(buffer)) != -1)
{
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
}

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
-
5@quikchange: There's no need when you're using a ByteArrayOutputStream - where would it buffer to? – Jon Skeet May 20 '10 at 14:41
9
A simple way would be to use org.apache.commons.io.IOUtils.toByteArray( inputStream )
, see apache commons io.

tangens
- 39,095
- 19
- 120
- 139