10

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();
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Subayan
  • 99
  • 1
  • 1
  • 8

2 Answers2

21

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;
    }
Community
  • 1
  • 1
Steve P.
  • 14,489
  • 8
  • 42
  • 72
11

This snippet should work for you:

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

    while ((line = input.readLine()) != null) { 
        last = line;
    }
    //do something with last!
xskxzr
  • 12,442
  • 12
  • 37
  • 77
Austin Henley
  • 4,625
  • 13
  • 45
  • 80