我需要一个将DataHandler转换为byte[]的代码片段。
此数据处理程序包含Image。
发布于 2011-01-13 19:17:51
只需使用以下代码即可完成此任务,而无需使用apache IO Commons。
final InputStream in = dataHandler.getInputStream();
byte[] byteArray=org.apache.commons.io.IOUtils.toByteArray(in);发布于 2012-04-20 22:50:47
你可以这样做:
public static byte[] toBytes(DataHandler handler) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
handler.writeTo(output);
return output.toByteArray();
}发布于 2011-01-13 01:28:33
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();
}注意,ByteArrayOutputStream.toByteArray()会创建内部字节数组的副本。
https://stackoverflow.com/questions/4671625
复制相似问题