Java I/O How to - Reverse a file








Question

We would like to know how to reverse a file.

Answer

 //w  w w .ja v a  2  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();
  }
}