Divide the code into small chunks, for example, to read a byte block (in your case 8 bytes) you need to know 3 things:
- In which file to read
- Where to start reading
- How many bytes to read / size of the block
Seeing this as one step would leave you with a method that returns a byte[] array, taking the above 3 points as parameters, for example:
private byte[] readByteBlock(InputStream in, int offset, int noBytes) throws IOException {
byte[] result = new byte[noBytes];
in.read(result, offset, noBytes);
return result;
}
The next step would be, to open the file and call this method for every byte block in the file. You start reading the file at position zero, call that method once, do something with the result, and call it all over at position = (previousPos) + blockSize. This chunk of code could be put in another method, for example:
public byte[][] toByteArray(File file, int byteBlockSize) throws IOException {
InputStream in = new FileInputStream(file);
long noOfBlocks = (long) Math.ceil((double)file.length() / (double)byteBlockSize);
byte[][] result = new byte[(int)noOfBlocks][byteBlockSize];
int offset = 0;
for(int i = 0; i < result.length; i++) {
result[i] = readByteBlock(in, offset, byteBlockSize);
}
return result;
}
This returns a byte[][] array with the first index as the byteBlockNumber (first 8 bytes, second 8 bytes, third 8 bytes, ...) and the second index each individual byte:
byte[0][0]: the first byte block's first byte
byte[0][7]: the first byte block's second byte
byte[1][2]: the second byte block, third byte
etc..
In the example code above the byte[][] array is initialized like:
long noOfBlocks = (long) Math.ceil((double)file.length() / (double)byteBlockSize);
byte[][] result = new byte[noOfBlocks][byteBlockSize];
So the number of blocks is the number of overall bytes in the file divided by the size of the byte blocks (8 in your example). Assuming the file has 9 bytes and the block size is 8, this would result 1,sth and rounded to 1, so you won't have space for the last byte, that's why Math.ceil() is used to round up to whatever the division gives. Math.ceil(9 / 8) -> 2, and those 2 are enough to hold the first block of 8 bytes, and the last byte in a second block.
Files.readAllBytes?