關於BufferefReader.readLine()方法的理解


  有以下代碼:      

 1 BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
 2 String msg=null;
 3 System.out.println("out of while loop!");
 4 while((msg=localReader.readLine())!=null){
 5     System.out.println(msg)
 6     if(msg.equals("bye")){
 7         break;
 8     }
 9                     
10 }    

 

  本來以為localReader.readLine()讀取不到數據時會返回null,結果執行代碼后不輸入數據時一直停留在while循環體內等待,故readLine()方法是一個阻塞函數。Java API文檔如下描述:

public String readLine()throws IOException
  Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

  表示該方法讀取一行文本,當遇到換行符"\n",回車符"\r"或者回車符后面緊跟着換行符時,該行結束並返回。沒有數據時,將會一直處於等待狀態。因此在進行網絡連接時,應該避免使用該方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM