The documentation says that one should not use available()
method to determine the size of an InputStream
. How can I read the whole content of an InputStream
into a byte array?
InputStream in; //assuming already present
byte[] data = new byte[in.available()];
in.read(data);//now data is filled with the whole content of the InputStream
I could read multiple times into a buffer of a fixed size, but then, I will have to combine the data I read into a single byte array, which is a problem for me.
The simplest approach IMO is to use Guava and its ByteStreams
class:
byte[] bytes = ByteStreams.toByteArray(in);
Or for a file:
byte[] bytes = Files.toByteArray(file);
Alternatively (if you didn't want to use Guava), you could create a ByteArrayOutputStream
, and repeatedly read into a byte array and write into the ByteArrayOutputStream
(letting that handle resizing), then call ByteArrayOutputStream.toByteArray()
.
Note that this approach works whether you can tell the length of your input or not - assuming you have enough memory, of course.