简体   繁体   English

如何将.txt文件的最后5行读入Java

[英]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 我将如何以降序读取最后五个条目,即从JoeBloggs-那里

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 . 您可以将行添加到List ,例如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. 一种非常简单的方法是使用Apache Commons Collections库中的CircularFifoBuffer类。 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. 因此,您将创建一个大小为5的CircularFifoBuffer ,然后将所有行添加到其中。 At the end, it'd contain just the last five lines of the file. 最后,它仅包含文件的最后五行。

we can use MemoryMappedFile for printing last 5 lines: 我们可以使用MemoryMappedFile打印最后5行:

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: RandomAccessFile打印最后5行:

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. 按照此代码使用Collectios改进核心Java逻辑。

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 ]. 注意:在numOfLastline和文件[而不是此Text.txt ]中提供所需的最后行号。

Try this code, a list of length 5 is scanned through all the lines, finally the list is reversed. 尝试使用此代码,将在所有行中扫描长度为5的列表,最后将该列表反转。 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. 这给了最后5行。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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