首页javanio_bufferJava 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("main.java");
    FileInputStream inFile = new FileInputStream(aFile);
    FileChannel inChannel = inFile.getChannel();
    ByteBuffer lengthBuf = ByteBuffer.allocate(8);
    while (true) {
      if (inChannel.read(lengthBuf) == -1) {
        break;
      }
      lengthBuf.flip();
      int strLength = (int) lengthBuf.getDouble();
      ByteBuffer buf = ByteBuffer.allocate(2 * strLength + 8);
      if (inChannel.read(buf) == -1) {
        break;
      }
      buf.flip();
      byte[] strChars = new byte[2 * strLength];
      buf.get(strChars);
      System.out.println(strLength);
      System.out.println(ByteBuffer.wrap(strChars).asCharBuffer());
      System.out.println(buf.getLong());
      lengthBuf.clear();
    }
    inFile.close();
  }
}