注:当前文件中的数据顺序:低位在前、高位在后
Java对十六进制文件的读取,尤其是使用readInt()和readDouble()方法时必须要对数据进行转换,这样才可以避免读到的数据出错。
我们先提供一个数据转换的类,这样可以便于后面的数据转换:
类名:ByteToOther
方法:
public int intFromByte(byte[] temp){
int value = 0;
// value = (((temp[0] & 0xff) << 24) | ((temp[1] & 0xff) << 16) | ((temp[2] & 0xff) << 8) | (temp[3] & 0xff));
value = ((temp[0] & 0xff) | ((temp[1] & 0xff) << 8) | ((temp[2] & 0xff) << 16) | ((temp[3] & 0xff) << 24));
return value;
}
public double doubleFromByte(byte[] temp){
byte tem = 0;
for(int i = 0; i < (temp.length + 1)/2; i ++){
tem = temp[i];
temp[i] = temp[temp.length - 1 - i];
temp[temp.length - 1 - i] = tem;
}
long val = (((long)(temp[0] & 0xff) << 56) | ((long)(temp[1] & 0xff) << 48) | ((long)(temp[2] & 0xff) << 40) | ((long)(temp[3] & 0xff) << 32) | ((long)(temp[4] & 0xff) << 24) | ((long)(temp[5] & 0xff) << 16) | ((long)(temp[6] & 0xff) << 8) | (long)(temp[7] & 0xff));
double value = Double.longBitsToDouble(val);
return value;
}
读取类:FileReader
public List<Point2D.Double> readFileCor(String path){
List<Point2D.Double> points = new ArrayList<Point2D.Double>();
File file = new File(path);
try {
FileInputStream in = new FileInputStream(file);
ByteToOther tTO = new ByteToOther();
for(int i = 0; i < file.length()/16; i ++){
Point2D.Double point = new Point2D.Double();
byte[] px = new byte[8];
byte[] py = new byte[8];
in.read(px);
in.read(py);
point.x = tTO.doubleFromByte(px);
point.y = tTO.doubleFromByte(py);
points.add(point);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return points;
}
注:如果文件中的数据顺序:高位在前、低位在后时,ByteToOther类应做如下处理
public int intFromByte(byte[] temp){
int value = 0;
value = (((temp[0] & 0xff) << 24) | ((temp[1] & 0xff)
<< 16) | ((temp[2] & 0xff) << 8) | (temp[3] &
0xff));
return value;
}
public double doubleFromByte(byte[] temp){
byte tem = 0;
long val = (((long)(temp[0] & 0xff) << 56) |
((long)(temp[1] & 0xff) << 48) | ((long)(temp[2] & 0xff)
<< 40) | ((long)(temp[3] & 0xff) << 32) |
((long)(temp[4] & 0xff) << 24) | ((long)(temp[5] & 0xff)
<< 16) | ((long)(temp[6] & 0xff) << 8) | (long)(temp[7]
& 0xff));
double value = Double.longBitsToDouble(val);
return value;
}