如何使用java读取文本文件中的最后一行 [英] how to read last line in a text file using java

查看:1668
本文介绍了如何使用java读取文本文件中的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making a log and I want to read the last line of the log.txt file, but I'm having trouble getting the BufferedReader to stop once the last line is read.

这是我的代码:

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


推荐答案

这里是一个很好的解决方案
< br>在你的代码中,你可以创建一个名为 lastLine 的辅助变量,并不断地将其重新初始化为当前行,如下所示:

Here's a good solution.

In your code, you could just create an auxiliary variable called lastLine and constantly reinitialize it to the current line like so:

    String lastLine = "";

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

这篇关于如何使用java读取文本文件中的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆