Memory-Mapped Files : Memory File « File « Java Tutorial






import java.io.File;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MainClass {
  public static void main(String[] args) throws Exception {
    File aFile = new File("C:/test.bin");
    RandomAccessFile ioFile = new RandomAccessFile(aFile, " rw");

    FileChannel ioChannel = ioFile.getChannel();
    final int PRIMESREQUIRED = 10;
    long[] primes = new long[PRIMESREQUIRED];

    int index = 0;
    final long REPLACEMENT = 999999L;

    final int PRIMECOUNT = (int) ioChannel.size() / 8;
    MappedByteBuffer buf = ioChannel.map(FileChannel.MapMode.READ_WRITE, 0L, ioChannel.size())
        .load();
    ioChannel.close();

    for (int i = 0; i < PRIMESREQUIRED; i++) {
      index = 8 * (int) (PRIMECOUNT * Math.random());
      primes[i] = buf.getLong(index);
      buf.putLong(index, REPLACEMENT);
    }

    for (long prime : primes) {
      System.out.printf("%12d", prime);
    }
    ioFile.close();
  }
}








11.53.Memory File
11.53.1.Memory-Mapped Files