Sunday, 26 May 2019

Java: Read last n lines of a file


Apache commons io library provides 'ReversedLinesFileReader' class to read the file contents in reverse way (Last line first).

Example
try (ReversedLinesFileReader reader = new ReversedLinesFileReader(file, Charset.forName("utf-8"));) {
         while (counter < numLines) {
                  System.out.println(reader.readLine());
                  counter++;
         }
}

App.java
package com.sample.app;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

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

public class App {

 public static void readLastNLines(File file, int numLines) throws IOException {
  int counter = 0;

  try (ReversedLinesFileReader reader = new ReversedLinesFileReader(file, Charset.forName("utf-8"));) {
   while (counter < numLines) {
    System.out.println(reader.readLine());
    counter++;
   }
  }

 }

 public static void main(String args[]) throws IOException {
  File file = new File("/Users/krishna/Documents/test.txt");
  readLastNLines(file, 5);
 }

}

test.txt
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Line 11
Line 12

Output
Line 12
Line 11
Line 10
Line 9
Line 8

Source code of ReversedLinesFileReader



You may like



No comments:

Post a Comment