I need a code snippt for converting DataHandler to byte[].
This data handler contains Image.
It can be done by using below code without much effort using apache IO Commons.
final InputStream in = dataHandler.getInputStream();
byte[] byteArray=org.apache.commons.io.IOUtils.toByteArray(in);
                        You can do it like this:
public static byte[] toBytes(DataHandler handler) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    handler.writeTo(output);
    return output.toByteArray();
}
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With