原文链接:http://www.iteye.com/problems/42079
灰常感谢回答问题的大神啊!!!
C++ 用fwrite写入文件的字节顺序是从低到高(左低到右高)也就是 是little-endian方式, 而在用java读取文件的时候会用到java.io.DataInputStream读取,它的数据格式是从高到低(左高到右低) 也就是big-endian方式。所以需要更改写入顺序。
有以下两种方法:
1. 可以使用commons-io中的类SwappedDataInputStream
commons-io包可以到apache上下载 http://commons.apache.org/io/download_io.cgi
2. 另外可以使用ByteBuffer来完成,而不需要自己考虑,如何将字节数组转换为其他数据类型. 使用ByteBuffer,可以设置字节顺序.
ByteBuffer简单的例子
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class ByteBufferTest {
public static void main(String[] args) {
//将字节数组转换为int类型
byte[] bytes = {0,0,0,1};
ByteBuffer buffer = ByteBuffer.wrap(bytes);
System.out.println(buffer.getInt());
ByteBuffer buffer2 = ByteBuffer.wrap(bytes);
buffer2.order(ByteOrder.LITTLE_ENDIAN);
System.out.println(buffer2.getInt());
}
}