我怎么能从变量中删除字符串后得到它


public class PortReader implements SerialPortEventListener {
    @Override
    public void serialEvent(SerialPortEvent event) {
        while(event.isRXCHAR() && event.getEventValue() > 0) {
            try {
                String receivedData = serialPort.readString(event.getEventValue());
                tempData = tempData.concat(receivedData);
                System.out.println(tempData);
            }
            catch (SerialPortException ex) {
                System.out.println("Error in receiving response from port: " + ex);
            }
        }
    }
}

我想从变量tempData中删除字符串。如果我把tempData = "";放在println的后面。我不知道为什么?有人能帮我弄明白吗?如果我不从变量中删除字符串,几分钟后我的CPU使用率就太高了。我从GPS天线接收到字符串,我从中得到NMEA。

使用StringBuffer或StringBuilder做这样的活动,在String上做这个操作在内存方面将是一个昂贵的操作。此外,看起来您想要从字符串中删除空格,在附加到StringBuffer

之前使用trim()函数
public class PortReader implements SerialPortEventListener {
    StringBuffer sb = StringBuffer();
    @Override
    public void serialEvent(SerialPortEvent event) {
        while (event.isRXCHAR() && event.getEventValue() > 0) {
            try {
                String receivedData = serialPort.readString(event
                        .getEventValue());
                // check if string is not null before trim
                sb.append(receivedData == null ? "" : receivedData.trim());
                sb.append(",");
                //just print the receivedData in plac of whle sb again and again
                System.out.println(receivedData);
            } catch (SerialPortException ex) {
                System.out.println("Error in receiving response from port: "
                        + ex);
            }
        }
        //check if the comma is the last index if so remove that
        String tmpData = sb.toString();
        tmpData = tmpData.replaceAll(", $", "");
        //print the entire data now
        System.out.println(tmpData);
    }
}

相关内容

  • 没有找到相关文章

最新更新