Java : Read last n lines of a HUGE file

后端 未结 11 1789
温柔的废话
温柔的废话 2020-11-27 04:59

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 Com

11条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 05:25

    package com.uday;
    
    import java.io.File;
    import java.io.RandomAccessFile;
    
    public class TailN {
        public static void main(String[] args) throws Exception {
            long startTime = System.currentTimeMillis();
    
            TailN tailN = new TailN();
            File file = new File("/Users/udakkuma/Documents/workspace/uday_cancel_feature/TestOOPS/src/file.txt");
            tailN.readFromLast(file);
    
            System.out.println("Execution Time : " + (System.currentTimeMillis() - startTime));
    
        }
    
        public void readFromLast(File file) throws Exception {
            int lines = 3;
            int readLines = 0;
            StringBuilder builder = new StringBuilder();
            try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) {
                long fileLength = file.length() - 1;
                // Set the pointer at the last of the file
                randomAccessFile.seek(fileLength);
    
                for (long pointer = fileLength; pointer >= 0; pointer--) {
                    randomAccessFile.seek(pointer);
                    char c;
                    // read from the last, one char at the time
                    c = (char) randomAccessFile.read();
                    // break when end of the line
                    if (c == '\n') {
                        readLines++;
                        if (readLines == lines)
                            break;
                    }
                    builder.append(c);
                    fileLength = fileLength - pointer;
                }
                // Since line is read from the last so it is in reverse order. Use reverse
                // method to make it correct order
                builder.reverse();
                System.out.println(builder.toString());
            }
    
        }
    }
    

提交回复
热议问题