我要编写一个读取ecg
录制文件并将数据写入变量的程序。
我现在所有的都是inputstream
和bytebuffer
。
我从文档中了解到,前2个bytes
应该代表checksum
unint16,下一个bytes
下一个output += String.format("0x%02X", bC[2]);
应该代表magic number在 hex 等等......
但是,如果我执行下面的代码,它将无法正常工作,因为该数字的输出为0。
我的问题是我在缓冲区中做错了什么。这很奇怪,因为如果我将整个流写入一个数组,然后指向3 - 6元素的位置,输出将是:
public class Stream {
private String fileName;
private byte[] storageArray;
private int byteLength;
private byte[] magicNumber;
public Stream(String fileName) {
this.fileName = fileName;
try {
readIt();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readIt() throws IOException {
FileInputStream fileIn = new FileInputStream("ecg-file");
//for skipping to the desired beginning of the byte stream
fileIn.skip(0);
setByteLength(fileIn.available());
storageArray = new byte[getByteLength()];
fileIn.read(getStorageArray());
fileIn.close();
}
public String getCRCNumber () {
ByteBuffer twoByte = ByteBuffer.wrap(getStorageArray());
twoByte.order(ByteOrder.LITTLE_ENDIAN);
//the missing bytes @ the beginning for the int
twoByte.put((byte)0x00);
twoByte.put((byte)0x00);
//shift the start position per 2 bytes
// and read the first 2 bytes of the inputstream into the buffer
twoByte.position(0x02);
twoByte.put(getStorageArray(), 0, 2);
twoByte.flip();
//creates the int number of the 4 bytes in the buffer
int result = twoByte.getInt();
String output = "";
String b = "\n";
return output += Integer.toString(result);
}
public int getByteLength() {
return byteLength;
}
public void setByteLength(int byteLength) {
this.byteLength = byteLength;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public byte[] getMagicNumber() {
return magicNumber;
}
public void setMagicNumber(byte[] magicNumber) {
this.magicNumber = magicNumber;
}
public byte[] getStorageArray() {
return storageArray;
}
public void setStorageArray(byte[] storageArray) {
this.storageArray = storageArray;
}
然后我将其颠倒阅读我得到了神奇的数字。
{{1}}
}
答案 0 :(得分:1)
你的第一个问题是使用available()。它所做的只是告诉你有多少数据可以被读取而没有阻塞,这很少引起人们的兴趣,并且Javadoc中有一个特定的警告,不会将其视为整个输入的长度。您真正感兴趣的是您需要多少数据。
幸运的是,有一个简单的解决方案。将输入流包装在DataInputStream,
中并按如下方式读取:
short crc16 = in.readShort();
// check the CRC
String hexString = "0x"+(Integer.toString(in.readInt(), 16));
// ...
等。见Javadoc。
skip(0)
在您的代码中不执行任何操作,因为您打开文件时已经是这样。
我不知道你的意思是'把它翻过来'。