什么 Java class 允许以二进制和 ASCII 写入文件?

What Java class allows to write to a file, both in Binary and ASCII?

我需要写文件,Headers ASCII 和二进制值。

目前,我正在使用这个:

File file = new File("~/myfile");
FileOutputStream out = new FileOutputStream(file);
// Write in ASCII
out.write(("This is a header\n").getBytes());
// Write a byte[] is quite easy
byte[] buffer = new buffer[4];
out.write(buffer, 0, 4);
// Write an int in binary gets complicated
out.write(ByteBuffer.allocate(4).putInt(6).array());
//Write a float in binary gets even more complicated
out.write(ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN)
        .putFloat(4.5).array());

问题是这样写(就性能而言)非常慢,比实际用 ASCII 写值慢得多。但它应该更短,因为我写的数据更少。

我看过其他的Java类,我觉得要么只能写ASCII,要么只能写Binary。

对于这个问题,您还有其他建议吗?

您可以使用FileOutputStream 来写入二进制文件。要包含文本,您必须在写入流之前将其转换为 byte[]。

The problem is that it's very long to write that way, way longer than writing the values in ASCII actually. But it should be shorter since in I'm writing less data.

混合文本和数据很复杂且容易出错。数据的大小确实很重要,但数据的复杂性很重要。如果你想让事情变得简单,我建议考虑使用 DataOutputStream。

要执行您的示例,您可以这样做

DataOutputStream out = new DataOutputStream(
    new BufferedOutputStream(
        new FileOutputStream("~/myfile")));
// Write in ASCII
out.write("This is a header\n".getBytes());
// Write a 32-bit int
out.writeInt(6);
//Write a float in binary
out.writeFloat(4.5f);

out.flush(); // the buffer.