Java Serial read \ u0002如何删除?

问题描述 投票:0回答:2

我正在使用RFID阅读器ID-12LA和Java RxTx库。

正在从阅读器加载数据,但数据:“ \ u000267009CB3541C”

如何删除\ u0002?卡ID为67009CB3541CSystem.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());

                        }

    });

我需要获取一个代表卡代码的字符串。我需要一个卡号读取器,然后才能访问。

java rfid rxtx
2个回答
0
投票

我不知道该RFID阅读器使用的协议,但是使用java.io.Reader似乎并不安全。如果将原始字节读入字符串,则使用字符集对数据进行编码时可能会损坏数据。

[设备似乎发送回一个响应字节(在这种情况下为02),后跟表示卡ID的ASCII字节。因此,避免使用InputStreamReader。相反,先读取第一个字节,然后读取字节,直到遇到换行符并将其转换为String。 (在转换时省略了字符集-您不想依赖系统的默认字符集!)

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);

0
投票

然后您确实可以按如下所示替换它:

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

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

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

inputLine = inputLine.substring(1);
© www.soinside.com 2019 - 2024. All rights reserved.