Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Read fixed number of bytes from a file in a loop in JAVA?

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.

like image 856
Usama Sarwar Avatar asked Sep 15 '13 11:09

Usama Sarwar


1 Answers

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.

like image 119
McDowell Avatar answered Sep 26 '22 00:09

McDowell