Java I/O How to - Map FileChannel to an IntBuffer and read from the IntBuffer








Question

We would like to know how to map FileChannel to an IntBuffer and read from the IntBuffer.

Answer

/*  w  w w . j  av  a2 s  . c o m*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;

public class MainClass {
  public static void main(String[] args) throws IOException {
    FileChannel fc = new FileInputStream(new File("temp.tmp")).getChannel();
    IntBuffer ib = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()).asIntBuffer();
    while (ib.hasRemaining())
      ib.get();
    fc.close();
  }
}