我有一个已知大小的 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 )
关于java - 如何将 Java FloatBuffer(或任何 Buffer)保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/735600/