我目前有一个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设置为little endian,然后从原始(big endian)缓冲区中读取" getInt"值,然后将该值" setInt"设置为little endian缓冲区。 我想有个更好的方法...
您是否为此尝试过Apache公共资源(commons.apache.org/io/api-release/org/apache/commons/io/)?
为Apache Commons +1:没有重新发明轮子:)
Endianess对于byte []没有意义。 字节序仅对多字节数据类型(如short,int,long,float或double)起作用。 正确选择字节序的正确时间是将原始数据写入字节并读取实际格式时。
如果给定了byte [],则必须解码原始数据类型,然后使用不同的字节序重新编码它们。 我相信您会同意这是a)不容易做到或不理想b)无法自动完成。
这是我解决类似问题的方法,希望正确获取要写入输出文件的整数的"字节序":
byte[] theBytes = /* obtain a byte array that is the input */
ByteBuffer byteBuffer = ByteBuffer.wrap(theBytes);
ByteBuffer destByteBuffer = ByteBuffer.allocate(theBytes.length);
destByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
IntBuffer destBuffer = destByteBuffer.asIntBuffer();
while (byteBuffer.hasRemaining())
{
int element = byteBuffer.getInt();
destBuffer.put(element);
/* Could write destBuffer int-by-int here, or outside this loop */
}
可能有更有效的方法来执行此操作,但是对于我的特殊问题,当我将元素复制到新缓冲区时,我不得不对元素进行数学转换。 但这仍然可以解决您的特定问题。