How to read last 5 lines of a .txt file into java

java get last n lines
java randomaccessfile read last line of file
how to read a particular string from a file in java
java read file line by line scanner
java read first and last line of file
read string line by line java
reversedlinesfilereader
how to read last line of a file in java using bufferedreader

I have a text file that consists of several entries such as:

hello
there
my
name
is
JoeBloggs

How would I read the last five entries in descending order, i.e. from JoeBloggs - there

I currently have code to read the LAST LINE only:

public class TestLastLineRead {
    public static void main(String[] args) throws Exception {           
        FileInputStream in = new FileInputStream(file.txt);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine = null, tmp;
        while ((tmp = br.readLine()) != null) {
            strLine = tmp;
        }

        String lastLine = strLine;
        System.out.println(lastLine);
        in.close();    
    }
}

You can add the lines to a List, e.g. a LinkedList. When the list has more than five lines, remove the first/last.

List<String> lines = new LinkedList<String>();
for(String tmp; (tmp = br.readLine()) != null;) 
    if (lines.add(tmp) && lines.size() > 5) 
        lines.remove(0);

Quickly read the last line of a text file?, Have a look at my answer to a similar question for C#. The code would be quite similar, although the encoding support is somewhat different in Java. Basically� Java program to read file from the last line, read last n lines of a file, read file from the end. In Java it can be done using RandomAccessFile which has a seek method to set the file-pointer offset, measured from the beginning of the file.

One very easy way would be to use the CircularFifoBuffer class from the Apache Commons Collections library. It's basically a list of a fixed size that discards old elements when it's full and you add new ones. So you'd create a CircularFifoBuffer of size 5, then add all the lines to it. At the end, it'd contain just the last five lines of the file.

How to Read File From The Last Line in Java, Java program to read file from the last line, read last n lines of a file, read file Let's say you have a file aa.txt which has the following content- as far as I know The fastest way to read the last line of a text file is using FileUtils Apache class which is in "org.apache.commons.io". I have a two-million-line file and by using this class, it took me less than one second to find the last line.

we can use MemoryMappedFile for printing last 5 lines:

private static void printByMemoryMappedFile(File file) throws FileNotFoundException, IOException{
        FileInputStream fileInputStream=new FileInputStream(file);
        FileChannel channel=fileInputStream.getChannel();
        ByteBuffer buffer=channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
        buffer.position((int)channel.size());
        int count=0;
        StringBuilder builder=new StringBuilder();
        for(long i=channel.size()-1;i>=0;i--){
            char c=(char)buffer.get((int)i);
            builder.append(c);
            if(c=='\n'){
                if(count==5)break;
                count++;
                builder.reverse();
                System.out.println(builder.toString());
                builder=null;
                builder=new StringBuilder();
            }
        }
        channel.close();
    }

RandomAccessFile to print last 5 lines:

private static void printByRandomAcessFile(File file) throws FileNotFoundException, IOException{
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        int lines = 0;
        StringBuilder builder = new StringBuilder();
        long length = file.length();
        length--;
        randomAccessFile.seek(length);
        for(long seek = length; seek >= 0; --seek){
            randomAccessFile.seek(seek);
            char c = (char)randomAccessFile.read();
            builder.append(c);
            if(c == '\n'){
                builder = builder.reverse();
                System.out.println(builder.toString());
                lines++;
                builder = null;
                builder = new StringBuilder();
                if (lines == 5){
                    break;
                }
            }

        }
    }

Java read file line by line, Java read file line by line, Java readLine method, Read text file line by line into String using BufferedReader, Scanner, Files, RandomAccessFile example. I want to read the last n lines of a very big file without reading the whole file into any buffer/memory area using Java. I looked around the JDK APIs and Apache Commons I/O and am not able to locate one which is suitable for this purpose. I was thinking of the way tail or less does it in UNIX.

Try this code, a list of length 5 is scanned through all the lines, finally the list is reversed. I edited / modified your code, test it to see it's fully working.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Test
{
    public static void main(String[] args) throws Exception
    {
        ArrayList<String> bandWidth = new ArrayList<String>();
        FileInputStream in = new FileInputStream("file.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        String tmp;
        while ((tmp = br.readLine()) != null)
        {
            bandWidth.add(tmp);
            if (bandWidth.size() == 6)
                bandWidth.remove(0);
        }

        ArrayList<String> reversedFive = new ArrayList<String>();
        for (int i = bandWidth.size() - 1; i >= 0; i--)
            reversedFive.add(bandWidth.get(i));
        in.close();
    }
}

How to Read a Text File in Java, Reading a Text File. Start a new project for this. Call the package textfiles and the class FileData. Add an import statement just below the package line and before� Java Scanner class provides the nextLine() method to facilitates line by line of file's content. The nextLine() methods returns the same String as readLine() method. The Scanner class can also read a file form InputStream. Example of read a file line by line using Scanner class

If all it really does have to do is print last 5 lines:

        ArrayList<String> lines = new ArrayList<String>();

        String tmp="";
        while ((tmp = br.readLine()) != null) {
            lines.add(tmp);
        }
        for (int i = lines.size()-5; i < lines.size(); i++) {
            System.out.println(lines.get(i-1));
        }

Reading a File Line by Line in Java, Dealing with large text files or logs. Sometimes, these files can be absurdly large, with gigabytes or terabytes being stored, and reading through them in entirety is� 2. Java 8 Read File + Stream + Extra. This example shows you how to use Stream to filter content, convert the entire content to upper case and return it as a List.

Reading the Nth line from a file in Java, The readAllLines method returns a list of strings where each string is a line of text in the specified file. get(n) retrieves the string for the� Learn to read file to string in Java. Given examples use Files.readAllBytes(), Files.lines() (to read line by line) and FileReader & BufferedReader to read text file to String. Java 11 – Files.readString() API. With the new method readString() introduced in Java 11, it takes only a single line to read a file’s content in to String.

Java exercises: Read first 3 lines from a file, Last update on February 26 2020 08:08:15 (UTC/GMT +8 hours) Write a Java program to read first 3 lines from a file. Append this text.

How to read file in Java using Scanner Example, line 4 :This Java program shows How to read file using java.util.Scanner class. line 5 :-------------�

Comments
  • See also: Quickly read the last line of a text file?
  • If I'm not mistaken, you can't read a part of a file out of order. Its just not possible. You have to read it sequentially until you get to the end and then handle the lines you care about, discarding everything up unto it. I could be wrong though...
  • This really is the most elegant answer, if only because it solves the problem without helping the asker complete his/her homework.
  • The only thing I think will be problem is- this will have larger memory footprints in case of larger files.
  • @SukeshKumar -- no it won't; as I said, you can just use a five-line buffer. Only five lines will be stored.
  • It will still need to read the whole file though, which would make it slow given a large input file.
  • this answer is the best one I've seen so far, it only reads the end part of the file.
  • The second approch do not work in one corner case, if the file exactly has 5 lines which implies there are 4 '\n'(lets say there is no '\n' for last line). however the program do not append the first line(last line from last) to the final string as it do not find the 5th '\n' but seek reaches zero and for loop comes out. so, before breaking add a sysout to print the content of string builder.
  • +1 to counteract downvote. It's not a very good solution as it stores the whole file in memory unnecessarily, but it's a working solution nonetheless.
  • is there a way that this could be incorporated into a HTML table where by each CSV value goes into a table
  • Why not..? You can definitely integrate it in an HTML table. Could you please checkout this stackoverflow.com/questions/9501106/…. I have answered it a couple of minutes back!!
  • Storing the while file in memory is bad enough, but storing it twice?
  • for (int i=0; i<5; i++) { System.out.println(list.get(i)); }...I can do like that if i dont want to store in strline string.What problem if we store in twice..is it wrong...?
  • this answer is so bad