There is such a method that helps me convert my files to byte[]
private byte[] getBytes(File zipToSend) { byte[] buffer = new byte[(int) zipToSend.length()]; BufferedInputStream bos = null; try { bos = new BufferedInputStream(new FileInputStream(zipToSend)); bos.read(buffer); } catch (IOException e) { e.printStackTrace(); } finally { try { if (bos != null) { bos.close(); } } catch (IOException e) { e.printStackTrace(); } } return buffer; } There are 2 questions:
- But as far as I know the
read(buffer);methodread(buffer);it may not read all the bytes in the buffer ... Thus, I risk losing part of the bytes. - Do I dare to get OOM if I specify
byte[] buffer = new byte[(int) zipToSend.length()];? After all, the buffer size depends on the size of the file being transferred, and if this is a folder of 50+ MB in size ...
Here I wrote the second alternative method
private byte[] getBytes(File zipToSend) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedInputStream bos = null; byte[] buffer = new byte[16384]; int count; try { bos = new BufferedInputStream(new FileInputStream(zipToSend)); while ((count = bos.read(buffer, 0, buffer.length)) != -1) { baos.write(buffer, 0, count); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (bos != null) { bos.close(); } } catch (IOException e) { e.printStackTrace(); } } return baos.toByteArray(); } In this example, I exclude the possibility of losing bytes and getting OOM, but in this case the execution time is increased 10 times ...
But all the same for us, of course, it is more important to get a full amount of data.
Are my beliefs about the first example correct?
ByteArrayOutputStream, it still uses the buffer, and not the fact that it is no more than a simple array. At the same time, it allocates a small buffer, and then increases it as you add bytes, which means creating a new buffer, copying all values ​​into it, which takes more time. In the first method, everything is fine, but the byte array will weigh as much as the file. The file is fully respected, unless there is a physical disconnection of the carrier, or the system decides to forbid you to read it - selyaIOExceptionwillIOExceptionand you will not return the entire array - Chubatiy