我需要用 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 写入,要么仅用于二进制写入。
你对这个问题有什么其他建议吗?