Java : Read last n lines of a HUGE file

后端 未结 11 1785
温柔的废话
温柔的废话 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:04

    Here is the working for this.

        private static void printLastNLines(String filePath, int n) {
        File file = new File(filePath);
        StringBuilder builder = new StringBuilder();
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(filePath, "r");
            long pos = file.length() - 1;
            randomAccessFile.seek(pos);
    
            for (long i = pos - 1; i >= 0; i--) {
                randomAccessFile.seek(i);
                char c = (char) randomAccessFile.read();
                if (c == '\n') {
                    n--;
                    if (n == 0) {
                        break;
                    }
                }
                builder.append(c);
            }
            builder.reverse();
            System.out.println(builder.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题