Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best way to read the last line of a text file in Java?

Tags:

java

io

I was confused when I want to get the last line of a plain text file in Java. How can I do this? and which is the best way without using scanner?

Thanks

like image 970
Mr.James Avatar asked Sep 14 '11 13:09

Mr.James


People also ask

How do you read the last line of a text file in Java?

In Java, we can use the Apache Commons IO ReversedLinesFileReader to read the last few lines of a File .

How do you get to the end of a file in Java?

The Java error message Reached End of File While Parsing results if a closing curly bracket for a block of code (e.g, method, class) is missing. The fix is easy — just proofread your code.

How do you find the end of a line in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do you read the next line in a file in Java?

To read the line and move on, we should use the nextLine() method. This method advances the scanner past the current line and returns the input that wasn't reached initially. This method returns the rest of the current line, excluding any line separator at the end of the line.


1 Answers

The simplest way to do it is simply to iterate over the lines in the file and stop when you reach the end. For example:

// I assume this is disposed properly etc
private static String getLastLine(BufferedReader reader) throws IOException {
    String line = null;
    String nextLine;
    while ((nextLine = reader.readLine()) != null) {
        line = nextLine;
    }
    return line;
}

This will return null for an empty reader.

Unless I knew I was going to have to read a really big file, that's what I'd do. Trying to do this by skipping straight to the last line is hard. Really hard, especially if you need a variable-width encoding such as UTF-8.

like image 85
Jon Skeet Avatar answered Sep 29 '22 03:09

Jon Skeet