12

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

This data handler contains Image.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Narendra
  • 5,635
  • 10
  • 42
  • 54

5 Answers5

30

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);
giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
Narendra
  • 5,635
  • 10
  • 42
  • 54
13

You can do it like this:

public static byte[] toBytes(DataHandler handler) throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    handler.writeTo(output);
    return output.toByteArray();
}
Weihong Diao
  • 718
  • 6
  • 12
4
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.

Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92
2

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;
}
matyig
  • 454
  • 5
  • 15
0

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.

Magnilex
  • 11,584
  • 9
  • 62
  • 84
Casey
  • 12,070
  • 18
  • 71
  • 107
  • 1
    `InputStream.available()` is not appropriate for this purpose. The `PipedInputStream` returned from the `DataHandler` returns the number of bytes available in its buffer before it blocks, not the total size. – dkarp Jan 12 '11 at 17:27
  • Interesting. I've seen this code in many places when dealing with web services. – Casey Jan 12 '11 at 17:31