2015-11-25 32 views
2

的我想這幾行:字符串比較不打破while循環

private String line; 
private final String stopChr= "#"; 

BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream())); 

while ((line = in.readLine()) != null) { 
     tcpData = tcpData + line; 
     if(line.equals(stopChr)) break; 
} 

爲什麼如果語句不是循環的突破時存在?

+2

最後一行是否只包含'#'? – Eran

+0

你可以發佈InputStream格式嗎? – ofnowhere

+0

$ 353323058181636,EV,D,T,567888.9,+ 12C,FFFFE000# –

回答

0

很可能該行不完全是「#」,例如它可能後面有空格。我建議你看看你的調試器或編輯器中的行是什麼,看看字符串究竟是什麼字符。

嘗試打印以下內容以幫助查看字符串的實際內容。

System.out.println(Arrays.toString(line.toCharArray()); 

如果你已經尾隨空格可以用trim

if (line.trim().equals(stopChar)) break; 
+0

需要讀取的字符串行是$ 353323058181636,EV,D,T,567888.9,+ 12C,FFFFE000# –

+0

使用'String.contains'代替。 –

+0

試過了,不行的也是 –

-1

刪除這些你將永遠不會得到空當的InputStream是從插座。相反,readLine()方法將會阻塞,直到獲得新數據。

+0

[BufferedReader.readLine在到達流末尾時返回null](https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()) –

+0

以便模擬數據接收案例,我從Hercules終端發送$ 353323058181636,EV,D,T,567888.9,+ 12C,FFFFE000#字符串。點擊發送按鈕後,斷開按鈕,while循環會因爲終端創建空值而中斷。 –

0

如果字符串包含其他字符,如在你的榜樣輸入$353323058181636,EV,D,T,567888.9,+12C,FFFFE000#(從@ PeterLawrey的回答您的評論),請使用以下代替String.equals

if(line.contains(stopChr)) break; 

如果專門停止結束字符,您也可以使用:

if(line.endsWith(stopChr)) break; 
+0

我試了兩次,沒有打破while循環 –

+0

我回應PeterLawrey的評論:「在這種情況下,字符串不是你認爲的那樣,我建議你在閱讀時打印出每個字符串。你發送數據的字符編碼是什麼,以及你正在讀取什麼字符編碼(這將是你的JVM的默認字符編碼)。 –

0

下面的代碼工作:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     String line = ""; 
     String data = ""; 
     while ((line = br.readLine()) != null) { 
      data += line; 
      if (line.contains("#")) 
       break; 
     } 

此外,代替contains(),您可以使用endsWith()來檢查文件的結尾。 你提供幫助。

0

爲#

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
    String line = ""; 
    String data = ""; 
    while (true) 
     { 
     line = br.readLine(); 

     // break if terminated 
     if (line==null) 
      break; 

     // Check : for debugging only 
     System.err.println("LINE : "+line); 

     // break if # 
     if (line.contains("#")) 
      { 
      // Get first part, part after, we dont care 
      int first=line.indexOf('#'); 
      data+=line.substring(0, first); 

      break; 
      } 

     else 
     data += line; 

    } 
    // See the result 
    System.out.println("DATA:"+data); 
+0

我也試過,沒有打破。我正在逐步調試,只有當我斷開終端時,執行行停在if(line == null)上。然後去行if(line.contains(「#」) 在執行過程中,如果沒有訪問if(line.contains(「#」)。 我可以放在這裏所有的代碼,它不是很長的 –

+0

可以你顯示你得到的是:LINE:? –

+0

我有沒有損失和沒有# $ 353323058181636,EV,D,T,567888.9,+ 12C,FFFFE000 –

0

問題解決之前讓一切。 readLine()函數需要結束字符串字符<CR>。只需將「#」替換爲「\ n」即可解決問題。感謝所有偉大的團隊。