Working with RandomAccessFile
import java.io.IOException;
import java.io.RandomAccessFile;
public class Diff {
public static void main(String args[]) {
RandomAccessFile fh1 = null;
RandomAccessFile fh2 = null;
int bufsize; // size of smallest file
long filesize1 = -1;
long filesize2 = -1;
byte buffer1[]; // the two file caches
byte buffer2[];
// check what you get as command-line arguments
if (args.length == 0 || args[0].equals("?")) {
System.err.println("USAGE: java Diff <file1> <file2> | ?");
System.exit(0);
}
// open file ONE for reading
try {
fh1 = new RandomAccessFile(args[0], "r");
filesize1 = fh1.length();
} catch (IOException ioErr) {
System.err.println("Could not find " + args[0]);
System.err.println(ioErr);
System.exit(100);
}
// open file TWO for reading
try {
fh2 = new RandomAccessFile(args[1], "r");
filesize2 = fh2.length();
} catch (IOException ioErr) {
System.err.println("Could not find " + args[1]);
System.err.println(ioErr);
System.exit(100);
}
if (filesize1 != filesize2) {
System.out.println("Files differ in size !");
System.out.println("'" + args[0] + "' is " + filesize1 + " bytes");
System.out.println("'" + args[1] + "' is " + filesize2 + " bytes");
}
// allocate two buffers large enough to hold entire files
bufsize = (int) Math.min(filesize1, filesize2);
buffer1 = new byte[bufsize];
buffer2 = new byte[bufsize];
try {
fh1.readFully(buffer1, 0, bufsize);
fh2.readFully(buffer2, 0, bufsize);
for (int i = 0; i < bufsize; i++) {
if (buffer1[i] != buffer2[i]) {
System.out.println("Files differ at offset " + i);
break;
}
}
} catch (IOException ioErr) {
System.err
.println("ERROR: An exception occurred while processing the files");
System.err.println(ioErr);
} finally {
try {
fh1.close();
fh2.close();
} catch (IOException ignored) {
}
}
}
}
Related examples in the same category