Java I/O How to - Reverse a file with RandomAccessFile








Question

We would like to know how to reverse a file with RandomAccessFile.

Answer

/*from w  ww . ja v a2  s . c o  m*/
import java.io.RandomAccessFile;

public class Main {
  public static void main(String[] argv) throws Exception {

    RandomAccessFile raf = new RandomAccessFile("a.dat", "rw");
    int x, y;

    for (long i = 0, j = raf.length() - 1; i < j; i++, j--) {
      raf.seek(i);
      x = raf.read();
      raf.seek(j);
      y = raf.read();

      raf.seek(j);
      raf.write(x);
      raf.seek(i);
      raf.write(y);

    }
    raf.close();
  }
}