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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar