Java - Memory-Mapped File I/O

Introduction

You can map a region of the file into physical memory and treating it as a memory array.

A special kind of byte buffer called MappedByteBuffer can perform memory-mapped file I/O.

The following code maps the whole file Main.java in a read-only mode.

It reads the file and displays the contents on the standard output.

Demo

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
  public static void main(String[] args) throws Exception {
    FileInputStream fis = new FileInputStream("Main.java");
    FileChannel fc = fis.getChannel();

    long startRegion = 0;
    long endRegion = fc.size();
    MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, startRegion,
        endRegion);//from  w  w w  . j a  v  a 2s . c  o m
    while (mbb.hasRemaining()) {
      System.out.print((char) mbb.get());
    }

    fc.close();
  }
}

Result