Java I/O How to - Create MappedByteBuffer from FileInputStream








Question

We would like to know how to create MappedByteBuffer from FileInputStream.

Answer

//www.j ava  2  s.c  o  m
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MainClass {
  private static final int LENGTH = 100; // Small

  public static void main(String[] args) throws Exception {
    MappedByteBuffer in = new FileInputStream("test.txt").getChannel().map(
        FileChannel.MapMode.READ_ONLY, 0, LENGTH);
    int i = 0;
    while (i < LENGTH)
      System.out.print((char) in.get(i++));
    System.out.println((char) in.get(i++));
  }
}