【发布时间】:2009-04-09 19:28:49
【问题描述】:
我有一个已知大小的 FloatBuffer,只想将数据转储到一个文件(二进制)中,以便在我的应用程序之外进行检查。最简单的方法是什么?
【问题讨论】:
我有一个已知大小的 FloatBuffer,只想将数据转储到一个文件(二进制)中,以便在我的应用程序之外进行检查。最简单的方法是什么?
【问题讨论】:
二进制输出更新:
// There are dependencies on how you create your floatbuffer for this to work
// I suggest starting with a byte buffer and using asFloatBuffer() when
// you need it as floats.
// ByteBuffer b = ByteBuffer.allocate(somesize);
// FloatBuffer fb = b.asFloatBuffer();
// There will also be endiance issues when you write binary since
// java is big-endian. You can adjust this with Buffer.order(...)
// b.order(ByteOrder.LITTLE_ENDIAN)
// If you're using a hex-editor you'll probably want little endian output
// since most consumer machines (unless you've got a sparc / old mac) are little
FileOutputStream fos = new FileOutputStream("some_binary_output_file_name");
FileChannel channel = fos.getChannel();
channel.write(byteBufferBackingYourFloatBuffer);
fos.close();
文本输出: 由于您希望这是可见的,我假设您需要一个文本文件。您需要使用 PrintStream。
// Try-catch omitted for simplicity
PrintStream ps = new PrintStream("some_output_file.txt");
for(int i = 0; i < yourFloatBuffer.capacity(); i++)
{
// put each float on one line
// use printf to get fancy (decimal places, etc)
ps.println(yourFloagBuffer.get(i));
}
ps.close();
没有时间发布完整的原始/二进制(非文本)版本。如果您想这样做,请使用FileOutputStream,获取FileChannel,然后直接写FloatBuffer(因为它是ByteBuffer)
【讨论】:
假设您希望数据为二进制:
以ByteBuffer 开头。致电asFloatBuffer 获取您的FloatBuffer。完成工作后,将ByteBuffer 保存到WritableByteChannel。
如果您已经拥有FloatBuffer,则可以使用put 从第2 步将其复制到缓冲区中。
一个低性能但更简单的方法是使用Float.floatToIntBit。
(显然要注意字节序。)
【讨论】:
这将遍历缓冲区支持的数组并输出每个浮点数。只需将文本文件和 floatBuffer 替换为您自己的参数即可。
PrintStream out = new PrintStream("target.txt");
for(float f : floatBuffer.array()){
out.println(f);
}
out.close();
【讨论】: