Read last n lines from a file using Java


Here I will show you how to read last n lines from a file using Java programming language. I am using text file for this example. Last “n” lines means, last 10 lines or 20 lines or 30 lines, etc. So “n” should be replaced by an appropriate non-zero positive integer value.

Obviously the tail of the file is harder to do and this is really a much more challenging situation than getting the first n (10, 20, 30 etc.) lines. Because you are habituated to read the file most of the time in forward direction.

I am using here Java 8 or later’s Stream API to read the last 10 lines from the file. If you want more lines to read then just replace the value 10 by your choice.


Eclipse 2020-06, At least Java 1.8

For gradle based project, the build.gradle script is given below:

plugins {
    id 'java-library'

sourceCompatibility = 12
targetCompatibility = 12

repositories {

dependencies {

Read Last n Lines

Let’s move on to the implementation of example…

Here is the source code in Java to read last n lines from a file.


import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class FileOperation {

	public static void main(String[] args) throws IOException {
		tailFile(Paths.get("Terms and Conditions 2012_FRL.txt"), 10).forEach(line -> System.out.println(line));

	public static final List<String> tailFile(final Path source, final int noOfLines) throws IOException {
		try (Stream<String> stream = Files.lines(source)) {
			FileBuffer fileBuffer = new FileBuffer(noOfLines);
			stream.forEach(line -> fileBuffer.collect(line));
			return fileBuffer.getLines();

	private static final class FileBuffer {
		private int offset = 0;
		private final int noOfLines;
		private final String[] lines;

		public FileBuffer(int noOfLines) {
			this.noOfLines = noOfLines;
			this.lines = new String[noOfLines];

		public void collect(String line) {
			lines[offset++ % noOfLines] = line;

		public List<String> getLines() {
			return IntStream.range(offset < noOfLines ? 0 : offset - noOfLines, offset)
					.mapToObj(idx -> lines[idx % noOfLines]).collect(Collectors.toList());


Look at the above source code how we are retrieving the last few lines from the given file.

The inner class FileBuffer that has two methods – collect() and getLines().

The collect() method will store maximum of 10 lines in the array. The getLines() method finally returns the lines of text string.

The tailFile() method iterates each line from the file and stores into lines array that overrides the lines if it exceeds size of 10 because it cannot store more than 10 line.

Testing the Program

Put the file Terms and Conditions 2012_FRL in project’s root directory and run the above class. You would see the following output in the console for the last 10 lines from the file.

17.2 Receiving Party may disclose Confidential Information of Disclosing Party in accordance with a judicial or other governmental order. In such case, the Receiving Party shall give the Disclosing Party notice prior to such disclosure to allow the Disclosing Party a reasonable opportunity to seek a protective order or equivalent.
17.3 The Contractor shall take all necessary actions to ensure that Confidential Information will not be removed from Contractors premises without written acceptance from Customer with the exception as stated in Article 5.4 – Contractor’s obligations of these Terms and Conditions.
17.4 Media containing the Work or the Work itself shall not be equipped with any devices that could interfere with their use (including to limitation: time locks, keys or bombs) or interfere with, delete or corrupt data.
17.5 The Contractor shall exclusively consider Customer as its ordering party for a given Project, once the Contractor has accepted to undertake the Work, and shall refrain from any and all immediate contact regarding this particular Project with the ultimate clients of Customer for localization and other services unless such a contact is expressly requested by Customer. Authorisation for such contact shall be given in writing by Customer.
17.6 The Contractor may not list the clients of the Customer in reference lists, similar documents or Websites, neither is granted any rights in the clients’ trademarks, trade names or logos, and the use of the same in any Contractor documentation or Websites, or otherwise, without the Customer’s prior written agreement. This relates only to Projects carried out under this Contract and does not relate to references to clients and Projects which are done through other MLVs or directly for the end clients.
Terms and Conditions
Confidential Page 6 of 6
17.7 In the case of violation of the provisions in Articles 16 - Confidentiality and 17 – Nondisclosure, Customer is entitled to claim penalty at the amount of 10 000 USD per incident. Without prejudice to its right to submit a claim for full compensation of damage, and it is entitled to terminate this Contract upon notice with immediate effect.
18.1. The parties agree that during the term of this Contract, Contractor is independent of Customer in the method used to provide the Work, is not subject to the hour-to-hour rule or employer type control of Customer, and is engaged by Customer only insofar as achieving a good end result. Contractor is responsible for the successful completion and performance of the Work. Contractor will be treated as an independent contractor for federal or state tax purposes with respect to services performed pursuant to this Contract. Contractor is responsible for paying Contractor’s estimated income and all self-employment tax. Contractor shall indemnify Customer from any and all taxes, interest and penalties Customer may incur as a result of the above treatment of Contractor.

Source Code


Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *