Mr.James
Mr.James

Reputation: 386

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

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

Upvotes: 5

Views: 2764

Answers (2)

Mark Bramnik
Mark Bramnik

Reputation: 42481

you can use RandomAccessFile 1. Go to the end of the file (new File("your_file").length()) 2. read char and use seek method of random access file in a loop. 3. when you seen "\n" (or whatever it is in your system) stop. 4. Re-read the file from the place you've stopped till the end of the file. This is optional if you memorize somehow what you've read so far

Just google for RandomAccessFile example.

Hope this helps

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500675

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.

Upvotes: 8

Related Questions