I need a code snippt for converting DataHandler to byte[].
This data handler contains Image.
I need a code snippt for converting DataHandler to byte[].
This data handler contains Image.
On
Is something like this what you are looking for?
public static byte[] getBytesFromDataHandler(final DataHandler data) throws IOException {
final InputStream in = data.getInputStream();
byte out[] = new byte[0];
if(in != null) {
out = new byte[in.available()];
in.read(out);
}
return out;
}
UPDATE:
Based on dkarp's comment this is incorrect. According to the docs for InputStream:
Returns the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream. The next caller might be the same thread or or another thread.
It looks like Costi has the correct answer here.
On
private static final int INITIAL_SIZE = 1024 * 1024;
private static final int BUFFER_SIZE = 1024;
public static byte[] toBytes(DataHandler dh) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(INITIAL_SIZE);
InputStream in = dh.getInputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ( (bytesRead = in.read(buffer)) >= 0 ) {
bos.write(buffer, 0, bytesRead);
}
return bos.toByteArray();
}
Beware that ByteArrayOutputStream.toByteArray() creates a copy of the internal byte array.
It can be done by using below code without much effort using apache IO Commons.