java中readLine()方法為什麼有的行讀不到?

來源:互聯網
上載者:User

標籤:ade   span   分行   java   main   null   為什麼   擷取   div   

  今天在使用java對IO操作時,readLine()輸出到控制台的行少了很多。後來發現readLine()實際上是一次讀取一行。如果我們不話readLine()讀取的行內容賦給一個字串的話,每直接調用一次readLine()方法,實際上就是往下讀一行。最後你會發現它變成了隔行讀取。

  下面兩段代碼中。直接system.out.println(br.readLine()),實際上就是輸出的while迴圈後的下一行。當我們將readLine()的結果賦值給一個變數是,輸出的是變數的內容而沒有再次調用readLine()方法,所以輸出的是正常內容。

  輸出檔案的部分行的內容:

 1     public static void main(String[] args) throws Exception { 2         //擷取讀取流 3         FileReader reader = new FileReader("C:\\Users\\楊華彬\\Desktop\\test.txt"); 4         BufferedReader br = new BufferedReader(reader); 5          6         while (br.readLine() != null) { 7             //注意這裡輸出的是readLine(),while迴圈中的和輸出中的readLine()方法被掉了兩次,所以會隔行讀取。 8             System.out.println(br.readLine()); 9         }10 11         //關閉讀取流12         br.close();13         reader.close();14     }

  正常輸出文本的額內容:

 1     public static void main(String[] args) throws Exception { 2         //擷取讀取流 3         FileReader reader = new FileReader("C:\\Users\\楊華彬\\Desktop\\test.txt"); 4         BufferedReader br = new BufferedReader(reader); 5          6         String string = null; 7         while ((string = br.readLine()) != null) { 8             //注意這裡輸出的是string,實際上readLine()方法只被調用了一次。 9             System.out.println(string);10         }11 12         //關閉讀取流13         br.close();14         reader.close();15     }

 

java中readLine()方法為什麼有的行讀不到?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.