我正在开发一个通过 rs232 编写命令和读取温度计输出的 java 程序。我正在使用JSSC。写入部分工作正常,但是当我读取输出并将其转换为字符串并使用 System.out.println() 打印时,会出现一些随机的新行。当我使用 System.out.write() 编写结果时,一切正常。我检查了字节码,没有找到任何 NL 字符。
这是我的代码:
public boolean openPort(int rate, int databits, int stopbit, int parity){
try {
serialPort.openPort();
serialPort.setParams(rate, databits, stopbit, parity);
int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR;//Prepare mask
serialPort.setEventsMask(mask);//Set mask
serialPort.addEventListener(new SerialPortReader());//Add SerialPortEventListener
return true;
} catch (SerialPortException e) {
System.out.println(e);
return false;
}
}
static class SerialPortReader implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR()){//If data is available
try {
byte buffer[] = serialPort.readBytes(event.getEventValue());
//with system.out.write
try {
System.out.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//with system.out.println
String readed = new String(buffer);
System.out.println(readed);
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
else if(event.isCTS()){//If CTS line has changed state
if(event.getEventValue() == 1){//If line is ON
System.out.println("CTS - ON");
}
else {
System.out.println("CTS - OFF");
}
}
else if(event.isDSR()){///If DSR line has changed state
if(event.getEventValue() == 1){//If line is ON
System.out.println("DSR - ON");
}
else {
System.out.println("DSR - OFF");
}
}
}
}
这是 println() 的输出:
--- START (C) ---
21.0,
21.1,21.3,
21.1
21.0,
21.2,21.3,
21.2
以及 write() 所需的输出
--- START (C) ---
21.0,21.1,21.3,21.1
21.0,21.1,21.3,21.1
您会说“为什么不直接使用 write()?”,但我需要将此输出转换为字符串。
有人能帮我吗?