Java I/O How to - Read a Binary File with ByteBuffer








Question

We would like to know how to read a Binary File with ByteBuffer.

Answer

/*w w  w.  j  a v  a 2  s. c o m*/
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
  public static void main(String[] args) throws Exception {
    File aFile = new File("C:/test.bin");
    FileInputStream inFile = new FileInputStream(aFile);
    FileChannel inChannel = inFile.getChannel();
    final int PRIMECOUNT = 6;
    ByteBuffer buf = ByteBuffer.allocate(8 * PRIMECOUNT);
    long[] primes = new long[PRIMECOUNT];
    while (inChannel.read(buf) != -1) {
      ((ByteBuffer) (buf.flip())).asLongBuffer().get(primes);
      for (long prime : primes) {
        System.out.printf("%10d", prime);
      }
      buf.clear();
    }
    inFile.close();
  }
}