Reverse a file with RandomAccessFile in Java
Description
The following code shows how to reverse a file with RandomAccessFile.
Example
/* www .j ava 2 s.c om*/
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();
}
}