Java – How to read last few lines of a File

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

pom.xml

	<dependency>
		<groupId>commons-io</groupId>
		<artifactId>commons-io</artifactId>
		<version>2.6</version>
	</dependency>

1. Test Data

A server log file sample

d:\\server.log

a
b
c
d
1
2
3
4
5

2. Read Last Line

2.1 Read the last 3 lines of a file.

TestReadLastLine.java

package com.mkyong.io;

import org.apache.commons.io.input.ReversedLinesFileReader;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class TestReadLastLine {

    public static void main(String[] args) {

        List<String> lines = readLastLine(new File("D:\\server.log"), 3);
        lines.forEach(x -> System.out.println(x));

    }

    public static List<String> readLastLine(File file, int numLastLineToRead) {

        List<String> result = new ArrayList<>();

        try (ReversedLinesFileReader reader = new ReversedLinesFileReader(file, StandardCharsets.UTF_8)) {

            String line = "";
            while ((line = reader.readLine()) != null && result.size() < numLastLineToRead) {
                result.add(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;

    }

}

Output


5
4
3

References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
logbasex
6 years ago

It’s not an elegant one.

Zeko
4 years ago

But how about reading the last MBs from the log. For example, the log file is 50MBs and you need to split in 5MB smaller logs. How can you read very last 5MBs from the log file?