Quickly read the last line of a text file?

2019-01-01 10:58发布

What's the quickest and most efficient way of reading the last line of text from a [very, very large] file in Java?

标签: java file io
8条回答
后来的你喜欢了谁
2楼-- · 2019-01-01 11:20

Apache Commons has an implementation using RandomAccessFile.

It's called ReversedLinesFileReader.

查看更多
永恒的永恒
3楼-- · 2019-01-01 11:33
try(BufferedReader reader = new BufferedReader(new FileReader(reqFile))) {

    String line = null;

    System.out.println("======================================");

    line = reader.readLine();       //Read Line ONE
    line = reader.readLine();       //Read Line TWO
    System.out.println("first line : " + line);

    //Length of one line if lines are of even length
    int len = line.length();       

    //skip to the end - 3 lines
    reader.skip((reqFile.length() - (len*3)));

    //Searched to the last line for the date I was looking for.

    while((line = reader.readLine()) != null){

        System.out.println("FROM LINE : " + line);
        String date = line.substring(0,line.indexOf(","));

        System.out.println("DATE : " + date);      //BAM!!!!!!!!!!!!!!
    }

    System.out.println(reqFile.getName() + " Read(" + reqFile.length()/(1000) + "KB)");
    System.out.println("======================================");
} catch (IOException x) {
    x.printStackTrace();
}
查看更多
登录 后发表回答