我正在swing
用 Java 构建一个接口,我构建了一个middleware
不断读取串行端口并保存即将发生的内容的接口String
,这就是我这样做的方式:
public class RFID {
private static RFIDReader rReader;
private static boolean state;
public RFID(RFIDReader rReader) {
this.rReader = rReader;
this.state = true;
}
public void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
(new Thread(new SerialReader(in))).start();
//(new Thread(new SerialWriter(out))).start();
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
public static class SerialReader implements Runnable {
InputStream in;
public SerialReader(InputStream in) {
this.in = in;
}
public void run() {
byte[] buffer = new byte[1024];
int len = -1;
String code;
try {
while (state == true && (len = this.in.read(buffer)) > -1) {
code = new String(buffer, 0, len);
if (code.length() > 1)
rReader.setCode(code);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void finish(){
state = false;
}
public static class SerialWriter implements Runnable {
OutputStream out;
public SerialWriter(OutputStream out) {
this.out = out;
}
public void run() {
try {
int c = 0;
while ((c = System.in.read()) > -1) {
this.out.write(c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
因此,当我尝试打印code
正在存储的内容时,它显示如下:
AC000F9
3
BB
实际上应该是这样的:
AC000F93BB
我在这里做错了什么?这种从byte[]
to的转换String
是不对的?
编辑: 我需要读取一个总共有 10 个字符的字符串。