代码是这样的
public static void main(String[] args) throws SerialPortException {
SerialPort serialPort = new SerialPort("COM1");
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_115200, 8, 1, 0);
if (serialPort.isOpened()) {
System.out.println("打开串口:" + serialPort.getPortName());
serialPort.addEventListener(serialPortEvent -> {
if (serialPortEvent.isRXCHAR()) {
while (true) {
if (serialPortEvent.getEventValue() > 0) {
try {
int b=serialPortEvent.getEventValue();
// byte[] bytes = serialPort.readBytes(b);
String hex= serialPort.readHexString(b);
//以16进制的方式读取串口返回数据
System.out.println("串口:" + serialPort.getPortName() + ",接收数据:" +hex);
String[] res=hex.split(" ");
String str="";
for (String r:res){
str+=r;
}
System.out.println(str);
String bw=hexStr2Str(str);
System.out.println("原文"+bw);
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
}
});
}
/**
* 16进制直接转换成为字符串(无需Unicode解码)
* @param hexStr
* @return
*/
public static String hexStr2Str(String hexStr) {
String str = "0123456789ABCDEF";
char[] hexs = hexStr.toCharArray();
byte[] bytes = new byte[hexStr.length() / 2];
int n;
for (int i = 0; i < bytes.length; i++) {
n = str.indexOf(hexs[2 * i]) * 16;
n += str.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
return new String(bytes);
}
代码等长度数据接收没问题,但如果数据长度变化后,新接收的数据还是原来数据的长度,但是新数据长度不足的地方被原数据的字符代替,如果长度比原数据长,则不显示后面的数据,这种情况怎么解决啊?