Convert DataHandler to Byte []

I need a software snippt to convert a DataHandler to byte[] .

This data handler contains Image .

+8
java
source share
5 answers

This can be done using the code below without much effort using Apache IO Commons.

 final InputStream in = dataHandler.getInputStream(); byte[] byteArray=org.apache.commons.io.IOUtils.toByteArray(in); 

Thanks,
Narendra

+22
source share

You can do it as follows:

 public static byte[] toBytes(DataHandler handler) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); handler.writeTo(output); return output.toByteArray(); } 
+11
source share
 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(); } 

Remember that ByteArrayOutputStream.toByteArray () creates a copy of the internal byte array.

+4
source share

I am using 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; } 
+1
source share

Something like this that 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 not true. According to docs for InputStream :

Returns the number of bytes that can be read (or skipped) from this input stream without blocking by the next caller for this input stream. The next caller may be the same thread or another thread.

Bone seems to have the right answer.

0
source share

Source: https://habr.com/ru/post/650985/


All Articles