java - 如何将 Java FloatBuffer(或任何 Buffer)保存到文件

标签 java file buffer

我有一个已知大小的 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/

相关文章:

java - 如何在 JBoss 7 中配置 PeriodicSizeRotatingFileHandler?

java.io.IOException : Cannot run program "sqlldr": CreateProcess error=2, 系统找不到指定的文件

java - 在没有加密的情况下在 Java 中使用 HTTPS

windows - 无法在 Windows/Cygwin 上使用 perl 确定文件创建时间

c - 动态生成文件内容(穷人的proc文件)

Python 缓冲 IO 以多管道结束早期流式传输 [BOUNTY]

c - 为什么要使用 shm_open?

java - 在无状态 EJB 中的 JTA 环境中执行手动回滚

c - 从标准输入检索字符

video - 将帧插入 FFmpeg 缓冲区