So, I have a code that reads a certain number of bytes from a file and returns a resulting array of bytes (this is mainly used to split files for sending over the network in the form of (ultimately) base64 based asc64 code).
It works great, except that when you create the last fragment of a file, it is not a complete fragment. Consequently, the resulting byte array is not populated. However, this is a constant size, which means that the file is reassembled, a whole bunch of additional data is added (possibly 0).
How can I make sure that the byte [] for the last fragment of the file really contains only the data that it needs? The code is as follows:
private byte[] readData(File f, int startByte, int chunkSize) throws Exception { RandomAccessFile raf = new RandomAccessFile(f, "r"); raf.seek(startByte); byte[] data = new byte[chunkSize]; raf.read(data); raf.close(); return data; }
So, if chunkSize is larger than the remaining bytes in the file, the full byte size [] is returned, but it is only half filled with data.
java file file-io byte bytearray
Erin drummond
source share