【发布时间】:2017-05-22 14:14:50
【问题描述】:
当我尝试在文件中写入具有如下值的二进制文件时:
public static main(String[] args){
ByteBuffer output = ByteBuffer.allocate(80);
output.order(ByteOrder.BIG_ENDIAN);
output.putDouble(545.5);
appendByteArrayInFile("c:/myPath/", "test.bin", output.array());
}
private static void appendByteArrayInFile(String exportDirectory, String fileName, byte[] toAppendInFile) {
if (toAppendInFile != null) {
File targetExport = createPathAndFile(exportDirectory + fileName);
try (FileOutputStream output = new FileOutputStream(targetExport, true)) {
output.write(toAppendInFile);
} catch (Exception e) {
// no
}
}
}
private static File createPathAndFile(String path) {
File targetExport = new File(path);
targetExport.getParentFile().mkdirs();
return targetExport;
}
问题是,当我查看生成的文件时,似乎 double 以 little-endian 样式放置,而当我将 ByteOrder 切换为 little-endian 时,double 以 big-endian 写入... 但是当我输入一个 int 时,字节序是正确的。
BigEndian 中的双精度输出:
01000000 10000001 00001100 00000000 00000000 00000000 00000000 00000000
littleEndian 中的双精度输出:
00000000 00000000 00000000 00000000 00000000 00001100 10000001 01000000
在 bigEndian 中使用 int 输出:
00000000 00000000 00000010 00100001
【问题讨论】:
标签: java endianness bytebuffer