I am using RFID reader ID-12LA and library for Java RxTx.
Loading data from reader but data: "\u000267009CB3541C"
How do I remove \u0002? Card ID is 67009CB3541C System.out.print is 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());
}
});
I need to get a String that represents the card code. I need a card number reader and then allow access.
I don’t know the protocol used by that RFID reader, but it looks like it is not safe to use a java.io.Reader. If you read raw bytes into a String, you risk corrupting data when it is encoded using a charset.
It appears the device sends back a response byte (02
in this case), followed by ASCII bytes representing the card ID. So, avoid using InputStreamReader; instead, read the first byte, then read bytes until you encounter a newline and convert them to a String. (Do not omit the charset when converting—you do not want to rely on the system’s default charset!)
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);