Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用java读取文本文件中的最后一行_Java_Io_Bufferedreader - Fatal编程技术网

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

如何使用java读取文本文件中的最后一行,java,io,bufferedreader,Java,Io,Bufferedreader,我正在制作日志,我想读取log.txt文件的最后一行,但在读取最后一行后,我很难让BufferedReader停止 这是我的密码: try { String sCurrentLine; br = new BufferedReader(new FileReader("C:\\testing.txt")); while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurren

我正在制作日志,我想读取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!

依我看,这不是一个重复的问题。看到这个答案了吗:你的链接是递归的?o、 奥萨特很搞笑。修复。我们正在检查while循环中的not null条件,为什么我们需要在其中嵌套if条件?@Subayan我的错误,修复了!