I have to read a fie where in every iteration I have to read 8 bytes form the file. For example in first iteration I'll read first 8 bytes and in second iteration next 8 and so on. How can this be done in Java?
public static byte[] toByteArray(File file) {
long length = file.length();
byte[] array = new byte[length];
InputStream in = new FileInputStream(file);
long offset = 0;
while (offset < length) {
int count = in.read(array, offset, (length - offset));
offset += length;
}
in.close();
return array;
}
I have found this, but I think what this code is doing is completely reading a file and making a byte array of file data. But I need to ready only that many bytes that I need in one iteration.
Use a DataInput for this type of processing:
private void process(File file) throws IOException {
try (RandomAccessFile data = new RandomAccessFile(file, "r")) {
byte[] eight = new byte[8];
for (long i = 0, len = data.length() / 8; i < len; i++) {
data.readFully(eight);
// do something with the 8 bytes
}
}
}
I've use a RandomAccessFile but a DataInputStream is a common alternative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With