【问题标题】:how to read last line in a text file using java [duplicate]如何使用java读取文本文件中的最后一行[重复]
【发布时间】:2013-07-04 18:58:11
【问题描述】:

我正在制作日志,我想读取 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();
    }
}

【问题讨论】:

标签: java io bufferedreader


【解决方案1】:

这个 sn-p 应该适合你:

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

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

【讨论】:

  • 我们正在检查 while 循环中的非空条件它自己为什么我们需要嵌套在里面的 if 条件?
  • @Subayan 我的错误,已修复!
【解决方案2】:

这是一个很好的 solution

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

    String lastLine = "";

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

【讨论】:

  • 您的链接是递归的? o.O
  • 太搞笑了。固定。
猜你喜欢
  • 2019-05-26
  • 2013-03-07
  • 2023-03-09
  • 2010-09-06
  • 2012-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多