簡體   English   中英

Java Serial read \ 如何刪除?

[英]Java Serial read \u0002 how to remove?

我正在使用 RFID 閱讀器 ID-12LA 和 Java RxTx 庫。

從讀取器加載數據但數據:“\67009CB3541C”

如何刪除 \? 卡 ID 是 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());

                        }

    });

我需要得到一個代表卡代碼的字符串。 我需要一個讀卡器,然后允許訪問。

那么你確實可以按如下方式替換它:

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

請注意表示一個字符的 \ 語法。

或者,如果您確定它始終是第一個字符:

inputLine = inputLine.substring(1);

我不知道該 RFID 閱讀器使用的協議,但看起來使用 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM