【发布时间】:2026-01-10 03:50:01
【问题描述】:
我目前有一个 Java ByteBuffer,它已经包含 Big Endian 格式的数据。然后我想以 Little Endian 的身份写入二进制文件。
以下是仍以 Big Endian 格式写入文件的代码:
public void writeBinFile(String fileName, boolean append) throws FileNotFoundException, IOException
{
FileOutputStream outStream = null;
try
{
outStream = new FileOutputStream(fileName, append);
FileChannel out = outStream.getChannel();
byteBuff.position(byteBuff.capacity());
byteBuff.flip();
byteBuff.order(ByteOrder.LITTLE_ENDIAN);
out.write(byteBuff);
}
finally
{
if (outStream != null)
{
outStream.close();
}
}
}
注意,byteBuff 是一个已经以 Big Endian 格式填充的 ByteBuffer。
我最后的手段是创建另一个缓冲区并将 ByteBuffer 设置为小端,然后从原始(大端)缓冲区读取“getInt”值,并将值“setInt”到小端缓冲区.我想有更好的方法......
【问题讨论】:
-
您是否为此尝试过 Apache commons (commons.apache.org/io/api-release/org/apache/commons/io/…)?
-
+1 for Apache Commons:不要重新发明* :)
标签: java bytebuffer endianness