Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting DataHandler to byte[]

I need a code snippt for converting DataHandler to byte[].

This data handler contains Image.

like image 745
Narendra Avatar asked Jan 12 '11 17:01

Narendra


3 Answers

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);
like image 89
Narendra Avatar answered Nov 13 '22 23:11

Narendra


You can do it like this:

public static byte[] toBytes(DataHandler handler) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    handler.writeTo(output);
    return output.toByteArray();
}
like image 41
Weihong Diao Avatar answered Nov 14 '22 01:11

Weihong Diao


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.

like image 4
Costi Ciudatu Avatar answered Nov 14 '22 01:11

Costi Ciudatu