How do I read an entire InputStream
into a byte array?
|
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[].
Internally this creates a ByteArrayOutputStream and copies the bytes to the output, then calls to ByteArray(). It handles large files by copying the bytes in blocks of 4MB. |
|||||||||||||||||||||
|
You need to read each byte from your
|
|||||||||||||||||||||
|
i don't know why this is found so difficult (some pages to scroll in google). so i write my favorite answer here on page number one if googled for "java inputstream to bytearray": Use Vanilla Javas "DataInputStream" and its "readFully" Method (exists at least since Java 1.4):
there are some other flavors of this method, but this i used all the time for this use case |
|||||||||||||||||||||
|
If you happen to use google guava, it'll be as simple as :
|
|||
|
Do you really need the image as a Other answers here show you how to read a file into a Java's standard API for reading (and writing) images is the ImageIO API, which you can find in the package
This will give you a Lookup the API documentation for ImageIO supports a number of image formats by default: JPEG, PNG, BMP, WBMP and GIF. It's possible to add support for more formats (you'd need a plug-in that implements the ImageIO service provider interface). See also the following tutorial: Working with Images |
||||
|
|
|||||||||||||||||||||
|
|
|||||
|
If you don't want to use the Apache commons-io library, this snippet is taken from the sun.misc.IOUtils class. It's nearly twice as fast as the common implementation using ByteBuffers:
|
|||
|
@Adamski: You can avoid buffer entirely. Code copied from http://www.exampledepot.com/egs/java.io/File2ByteArray.html (Yes, it is very verbose, but needs half the size of memory as the other solution.)
|
|||||||||||||||||||||
|
|
|||
|
I tried to edit @numan's answer with a fix for writing garbage data but edit was rejected. While this short piece of code is nothing brilliant I can't see any other better answer. Here's what makes most sense to me:
btw ByteArrayOutputStream need not be closed. try/finally constructs omitted for readability |
|||
|
Below Codes
OR
|
|||
|
|
|||||
|
Here is an optimized version, that tries to avoid copying data bytes as much as possible:
|
||||
|
I know its a bit late but I wanted to share this because I think the simplest solution is do something like this (removing try catch code for brevity+clarity):
|
|||||||||
|