Read file full content to a byte array with RandomAccessFile in Java
Description
The following code shows how to read file full content to a byte array with RandomAccessFile.
Example
//from w w w. j av a 2 s. co m
import java.io.RandomAccessFile;
public class Main {
public static void main(String args[]) throws Exception {
RandomAccessFile fh1 = new RandomAccessFile("a.txt", "r");
RandomAccessFile fh2 = new RandomAccessFile("b.txt", "r");
long filesize1 = fh1.length();
long filesize2 = fh2.length();
// allocate two buffers large enough to hold entire files
int bufsize = (int) Math.min(filesize1, filesize2);
byte[] buffer1 = new byte[bufsize];
byte[] buffer2 = new byte[bufsize];
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;
}
}
fh1.close();
fh2.close();
}
}