java - 关于BufferedReader中readLine读取最后一行的问题
巴扎黑
巴扎黑 2017-04-17 14:59:34
0
2
2002

public static void main(String[] args) throws Exception{

    BufferedReader in = new BufferedReader(new FileReader("Test3.txt"));
    String line =null;
    while((line=in.readLine())!=null)
    {
        System.out.println(line);
    }
}

想问一下通过readLine方法读取一个文本行。通过下列字符之一即可认为某行已终止:换行 ('\n')、回车 ('\r') 或回车后直接跟着换行,但是在最后一行的时候并没有换行或者回车的字符啊,此时为什么会读取到最后一行呢?按理说最后一行是不应该被读取到的。求解!

巴扎黑
巴扎黑

全部回覆(2)
Peter_Zhu

在BufferedReader中有一個private方法是用來判斷是否到達Stream的結尾的,如下:

  • @return the number of chars read into the buffer, or -1 if the end of the source stream has been reached.

 private int fillBuf() throws IOException {

而在rea​​dLine()中有一段是這麼寫的:

 while (true) {
    pos = end;
    if (fillBuf() == -1) {
        // If there's no more input, return what we've read so far, if anything.
        return (result.length() > 0) ? result.toString() : null;
    }
    ...
Ty80

這個可以看下BufferedReader的源碼,其實還有一種情況,就是讀到了文件結束位置(也就是最後一行),即使沒有n和r也會回傳這一行。

if (nextChar >= nChars) { /* EOF */
  if (s != null && s.length() > 0)
    return s.toString();
  else
    return null;
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!