Java I/O How to - Read file full content to a byte array with RandomAccessFile








Question

We would like to know how to read file full content to a byte array with RandomAccessFile.

Answer

// www .j  ava2  s. c o 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();
  }
}