[英]How to remove blank lines from a BufferedReader
我正在嘗試從串行調制解調器獲得響應並將其存儲到BufferedReader中。 這是輸出:
imsiAT + CIMI
imsi
imsi510011130957977
imsi
imsiOK
並且我想使用以下代碼獲取值為“ 510011130957977” :
os.print("AT+CIMI");
os.print("\n");
String responInput20000;
try {
while ((imsi = reader.readLine())!=null) {
System.out.println("imsi"+imsi);
txtOutput.insert(imsi.replace("\n", "").replace("\r", "").replace("OK", "").replace("AT+CIMI", "")+"\n", 0);
lblImsi.setText(imsi.replace("\n", "").replace("\r", "").replace("OK", "").replace("AT+CIMI", "").replace("\n\r",""));
if(imsi.equals("OK")){
break;
}
但是JTextArea
仍然包含兩個空行。 也許還有其他解決方案?
如果您不使用replace()
方法來滿足您的需要,那將更容易(並且更快):
while ((imsi = reader.readLine()) != null) {
if (!imsi.isEmpty() && !imsi.equals("OK") && !imsi.equals("AT+CIMI") {
txtOutput.insert(imsi);
lblImsi.setText(imsi);
}
}
無需替換這些字符串(您可以忽略它們)。 而且由於使用readLine()
讀取,因此您在字符串中將找不到任何換行符( \\r\\n
)!
您可以創建一個像這樣的方法,使用所有閱讀器內容並發現所需的價值:
private static String getValue(BufferedReader reader) throws IOException {
String value = null;
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
String str = line.substring("imsi".length());
if ("".equals(str)) {
continue;
}
if ("OK".equals(str)) {
break;
}
value = str;
}
return value;
}
您可以嘗試使用Matcher匹配正則表達式(在這種情況下為數字)
String[] sArr = new String[]{"imsiAT+CIMI","imsi510011130957977","imsiOK"};
Pattern pattern = Pattern.compile("\\d+");
// or if you know the precise number of digits (15 in example), use this..
// Pattern pattern = Pattern.compile("\\d{15}");
String output;
for (String s : sarr) {
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
output = matcher.group();
break;
}
}
System.out.println(output);
// or as a number
long l = l = Long.parseLong(output);
lblImsi.setText(output);
這對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.