HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

Convert InputStream to byte array in Java

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayjavainputstreambyteconvert

Problem

How do I read an entire InputStream into a byte array?

Solution

You can use Apache Commons IO to handle this and similar tasks.

The IOUtils type has a static method to read an InputStream and return a byte[].

InputStream is;
byte[] bytes = IOUtils.toByteArray(is);


Internally this creates a ByteArrayOutputStream and copies the bytes to the output, then calls toByteArray(). It handles large files by copying the bytes in blocks of 4KiB.

Code Snippets

InputStream is;
byte[] bytes = IOUtils.toByteArray(is);

Context

Stack Overflow Q#1264709, score: 1292

Revisions (0)

No revisions yet.