9

我正在制作日志,我想读取 log.txt 文件的最后一行,但是一旦读取最后一行,我就无法让 BufferedReader 停止。

这是我的代码:

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();
    }
}
4

2 回答 2

21

这是一个很好的解决方案

在您的代码中,您可以创建一个名为的辅助变量lastLine并不断将其重新初始化为当前行,如下所示:

    String lastLine = "";

    while ((sCurrentLine = br.readLine()) != null) 
    {
        System.out.println(sCurrentLine);
        lastLine = sCurrentLine;
    }
于 2013-07-07T06:28:17.600 回答
11

这个片段应该适合你:

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

    while ((line = input.readLine()) != null) { 
        last = line;
    }
    //do something with last!
于 2013-07-07T06:34:21.777 回答