开发者

converting DataHandler to byte[]

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

This data handler contains Imag开发者_Go百科e.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜