Java 串口读\u0002怎么去掉?

Java Serial read \u0002 how to remove?

我正在为 Java RxTx 使用 RFID reader ID-12LA 和库。

正在从 reader 加载数据,但数据为:“\u000267009CB3541C”

如何删除 \u0002?卡号为 67009CB3541C System.out.print 是 67009CB3541C

        BufferedReader input = new BufferedReader(new InputStreamReader(port.getInputStream()));
                        port.addEventListener(event -> {
                            if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                                try {
                                    String inputLine = input.readLine();
                                    inputLine.replace("\"\u0002\"", "");

                                    System.out.println("Read data: " + inputLine);
}
catch (IOException | URISyntaxException e) {
                            System.err.println(e.toString());

                        }

    });

我需要获取一个表示卡片代码的字符串。 我需要一个卡号reader然后允许访问

那么确实可以这样替换:

inputLine = inputLine.replace("\u0002", "");

注意表示一个字符的 \u0002 语法。

或者,如果您确定它始终是第一个字符:

inputLine = inputLine.substring(1);

我不知道那个 RFID reader 使用的协议,但看起来使用 java.io.Reader 并不安全。如果将原始字节读入字符串,则在使用字符集编码时可能会损坏数据。

设备似乎发回了一个响应字节(在本例中为 02),后跟表示卡 ID 的 ASCII 字节。所以,避免使用 InputStreamReader;相反,读取第一个字节,然后读取字节直到遇到换行符并将它们转换为字符串。 (转换时不要省略字符集——您不想依赖系统的默认字符集!)

InputStream input = port.getInputStream();

int code = input.read();
if (code != 2) {
    throw new IOException("Reader did not return expected code 2.");
}

ByteArrayOutputStream idBuffer = new ByteArrayOutputStream();
int b;
while ((b = input.read()) >= 0 && b != '\r' && b != '\n') {
    idBuffer.write(b);
}

String cardID = idBuffer.toString(StandardCharsets.UTF_8);