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
ByteStreamsclass:Or for a 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 theByteArrayOutputStream(letting that handle resizing), then callByteArrayOutputStream.toByteArray().Note that this approach works whether you can tell the length of your input or not – assuming you have enough memory, of course.