如何使用java 读取文本文件中的最后一行

我正在创建一个日志,我想读取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(); } } 

这是一个很好的解决方案 。

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

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

这段代码应该适合你:

  BufferedReader input = new BufferedReader(new FileReader(fileName)); String last, line; while ((line = input.readLine()) != null) { last = line; } //do something with last!