Narendra
Narendra

Reputation: 5773

converting DataHandler to byte[]

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

This data handler contains Image.

Upvotes: 13

Views: 44119

Answers (5)

Narendra
Narendra

Reputation: 5773

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);

Upvotes: 31

user147373
user147373

Reputation:

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.

Upvotes: 0

matyig
matyig

Reputation: 454

I use this code:

public static byte[] getContentAsByteArray(DataHandler handler) throws IOException {
    byte[] bytes = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    handler.writeTo(bos);
    bos.flush();
    bos.close();
    bytes = bos.toByteArray();

    return bytes;
}

Upvotes: 2

Weihong Diao
Weihong Diao

Reputation: 748

You can do it like this:

public static byte[] toBytes(DataHandler handler) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    handler.writeTo(output);
    return output.toByteArray();
}

Upvotes: 13

Costi Ciudatu
Costi Ciudatu

Reputation: 38235

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.

Upvotes: 3

Related Questions