how to read last line in a text file using java

Subayan picture Subayan · Jul 7, 2013 · Viewed 57k times · Source

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.

Here's my code:

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

Answer

Steve P. picture Steve P. · Jul 7, 2013

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