1

我需要用 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 写入,要么仅用于二进制写入。

你对这个问题有什么其他建议吗?

4

1 回答 1

0

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

问题是这样写很长,比实际用 ASCII 写值要长得多。但它应该更短,因为我写的数据更少。

混合文本和数据是复杂且容易出错的。数据的大小确实很重要,而数据的复杂性很重要。如果您想保持简单,我建议考虑使用 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.
于 2015-01-28T20:46:33.633 回答