2

我有一个已知大小的 FloatBuffer,只想将数据转储到一个文件(二进制)中,以便在我的应用程序之外进行检查。最简单的方法是什么?

4

3 回答 3

4

二进制输出的更新:

// 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

于 2009-04-09T19:44:57.873 回答
2

假设您希望数据为二进制:

ByteBuffer. 致电asFloatBuffer获取您的FloatBuffer. 完成工作后,将ByteBuffer输出保存到WritableByteChannel.

如果您已经拥有FloatBuffer它,则可以使用put.

一种低性能但更简单的方法是使用Float.floatToIntBit.

(显然,注意字节顺序。)

于 2009-04-09T19:52:28.497 回答
-1

这将遍历缓冲区支持的数组并输出每个浮点数。只需将文本文件和 floatBuffer 替换为您自己的参数即可。

PrintStream out = new PrintStream("target.txt");
for(float f : floatBuffer.array()){
  out.println(f);
}
out.close();
于 2009-04-09T19:51:12.617 回答