2013-07-07 90 views
5

我正在創建一個日誌,並且我想讀取log.txt文件的最後一行,但我無法在最後一行是BufferedReader時停止讀。如何使用java讀取文本文件中的最後一行

這裏是我的代碼:

try { 
    String sCurrentLine; 

    br = new BufferedReader(new FileReader("C:\\testing.txt")); 

    while ((sCurrentLine = br.readLine()) != null) { 
     System.out.println(sCurrentLine); 
    } 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    try { 
     if (br != null)br.close(); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
} 
+0

的http:// stackoverflow.com/questions/686231/java-quickly-read-the-last-line-of-a-text-file –

+2

IMO,這不是一個重複的問題。 –

+0

查看此答案:http://stackoverflow.com/a/11665098/548225 – anubhava

回答

14

這裏有一個很好的solution

在你的代碼,你可以只創建一個名爲lastLine輔助變量,它不斷地重新初始化到當前行,像這樣:

String lastLine = ""; 

    while ((sCurrentLine = br.readLine()) != null) 
    { 
     System.out.println(sCurrentLine); 
     lastLine = sCurrentLine; 
    } 
+3

您的鏈接是遞歸的嗎? O.O – Zong

+1

真是太好笑了。固定。 –

6

該段應爲你工作:

BufferedReader input = new BufferedReader(new FileReader(fileName)); 
    String last, line; 

    while ((line = in.readLine()) != null) { 
     last = line; 
    } 
    //do something with last! 
+0

我們在while循環中檢查not null條件它爲什麼我們需要if條件嵌套在裏面? – Subayan

+0

@Subayan我的錯誤,修復! –

相關問題