Java I/O How to - Seek file pointer position in binary file








Question

We would like to know how to seek file pointer position in binary file.

Answer

  /*from   w w w .  ja  v a  2 s.co m*/

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class Main {
  public static void main(String[] args) throws IOException {
    RandomAccessFile raf = new RandomAccessFile(new File("temp.tmp"), "rw");
    raf.writeInt(1);
    for (int i = 0; i < 10; i++) {
      raf.seek(raf.length() - 4);
      raf.writeInt(raf.readInt());
    }
    raf.close();

  }
}