简体   繁体   中英

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

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, ie 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 , eg 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);

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.

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;
                }
            }

        }
    }

Follow This Code To Improve Core Java Logic By Using Collectios.

import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Scanner;

    public class REVERSE {
        public static void main(String[] args) {
            ArrayList<String> al = new ArrayList<String>();
            try {
                Scanner sc = new Scanner(new FileReader("input.txt"));
                while (sc.hasNextLine()) {
                    al.add(sc.nextLine());
                }
                System.out.println(al.get(0));
                System.out.println(al.get(1));
                System.out.println(al.get(2));
                System.out.println(al.get(3));
                System.out.println(al.get(4));

                Collections.reverse(al);
                /*
                 * for (String s : al) { System.out.println(s); }
                 */
                System.out.println(al.get(0));
                System.out.println(al.get(1));
                System.out.println(al.get(2));
                System.out.println(al.get(3));
                System.out.println(al.get(4));
                /*
                 * for (int i = 0; i < al.size(); i++) {
                 * System.out.println(al.get(i)); }
                 */
            } catch (FileNotFoundException e) {

            }

        }
    }

Please try this code. It is working fine for me.

public static void main(String[] args)
{
    try
    {
        int numOfLastline = 10;
        BufferedReader reader = new BufferedReader(new FileReader("Text.txt"));
        int lines = 0;
        while (reader.readLine() != null)
            lines++;
        reader.close();

        System.out.println(lines);

        String printedLine = null;
        List<String> listForString = new ArrayList<String>();
        for (int i = lines - 1; i >= (lines - numOfLastline); i--)
        {
            printedLine = (String) FileUtils.readLines(new File("Text.txt"), "ISO-8859-1").get(i);
            System.out.println(printedLine);
            listForString.add(printedLine);
        }

        System.out.println("\n\n============ Printing in Correct order =============\n\n");
        Collections.reverse(listForString);

        for (int k = 0; k < listForString.size() ; k++)
        {
            System.out.println(listForString.get(k));
        }

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

Note : Provide your needed last line numbers at numOfLastline and file [instead of this Text.txt ].

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();
    }
}

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));
        }

Try this. This give for last 5 line.

 public static void main(String[] args) throws IOException {
            List<String > list =new ArrayList<String>();
            FileInputStream in = new FileInputStream("C:/adminconsole.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            String strLine ="", tmp;
            while ((tmp = br.readLine()) != null){ 
                //strLine =tmp+"\n"+strLine;
                list.add(tmp);
                }

            if(list.size()>5){
                for (int i=list.size()-1; i>=(list.size()-5); i--) {
                    System.out.println(list.get(i));
                }
            }else{
                for (int i=0; i<5; i++) {
            System.out.println(list.get(i));
        }

            }

        }
    }

First you have to read the file line by line and add each line to a list. Once the file is read completely, you can print each element in the list in reverse order as shown below:

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


public class FileReader {

    public static List<String> readFile() throws IOException {
        List<String> fileContents = new ArrayList<String>();
        FileInputStream fileInputStream = new FileInputStream("C:/Users/compaq/Desktop/file.txt");
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String strLine = null;
        while((strLine=bufferedReader.readLine())!=null) {
            fileContents.add(strLine);
        }
        fileInputStream.close();
        return fileContents;
    }

    public static void printFileInReverse(List<String> fileContents, int numberOfLines) {
        int counter = 0;
        for(int i=(fileContents.size()-1);i>=0;i--) {
            if(counter==numberOfLines) { break; }
            System.out.println(fileContents.get(i));
            counter++;
        }
    } 

    public static void main(String[] args) throws IOException {
        List<String> fileContents = new ArrayList<String>();
        fileContents = FileReader.readFile();
        int numberOfLines = 5;// Number of lines that you would like to print from the bottom of your text file.
        FileReader.printFileInReverse(fileContents, numberOfLines);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM