首页javareadJava I/O - 如何用ByteBuffer读取二进制文件

Java I/O - 如何用ByteBuffer读取二进制文件

我们想知道如何用ByteBuffer读取二进制文件。
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();
  }
}