Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read last line in a text file using java [duplicate]

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();
    }
}
like image 244
Subayan Avatar asked Jul 07 '13 06:07

Subayan


2 Answers

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;
    }
like image 187
Steve P. Avatar answered Sep 18 '22 21:09

Steve P.


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!
like image 32
Austin Henley Avatar answered Sep 18 '22 21:09

Austin Henley