我认为最简单且最不容易出错的方法是使用 ByteBuffer。这是一个包含两个测试用例的示例,第一个创建一个二进制文件,第二个读取它。请注意,您可以将字节编码设置为小端或大端。
import org.junit.Test;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class ByteStreamWriteRead {
  @Test
  public void write() throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(32);
    buffer.order(ByteOrder.BIG_ENDIAN);
    System.out.println("Putting: " + Math.PI + ", " + (float) Math.PI);
    buffer.putDouble(Math.PI);
    buffer.putFloat((float) Math.PI);
    File file = new File("C:/tmp/file.bin");
    file.createNewFile();
    try (FileOutputStream fos = new FileOutputStream(file)) {
      fos.write(buffer.array(), 0, buffer.position());
    }
  }
  @Test
  public void read() throws IOException {
    File file = new File("C:/tmp/file.bin");
    byte[] a = new byte[32];
    if (file.exists()) {
      try (FileInputStream fis = new FileInputStream(file)) {
        fis.read(a);
      }
      ByteBuffer buffer = ByteBuffer.wrap(a);
      buffer.order(ByteOrder.BIG_ENDIAN);
      System.out.println(buffer.getDouble());
      System.out.println(buffer.getFloat());
    } else {
      System.out.println("File doesn't exist");
    }
  }
}
请注意:上面的示例并未显示读取或写入文件的最有效方法。您应该使用缓冲的读取器/写入器并重用 ByteBuffer 一次读取一大块字节。那是特定于应用程序的。上面的示例仅显示了使用 ByteBuffer 和正确字节编码的逻辑。