Java : Read last n lines of a HUGE file

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

    Here is the best way I've found to do it. Simple and pretty fast and memory efficient.

    public static void tail(File src, OutputStream out, int maxLines) throws FileNotFoundException, IOException {
        BufferedReader reader = new BufferedReader(new FileReader(src));
        String[] lines = new String[maxLines];
        int lastNdx = 0;
        for (String line=reader.readLine(); line != null; line=reader.readLine()) {
            if (lastNdx == lines.length) {
                lastNdx = 0;
            }
            lines[lastNdx++] = line;
        }
    
        OutputStreamWriter writer = new OutputStreamWriter(out);
        for (int ndx=lastNdx; ndx != lastNdx-1; ndx++) {
            if (ndx == lines.length) {
                ndx = 0;
            }
            writer.write(lines[ndx]);
            writer.write("\n");
        }
    
        writer.flush();
    }
    

提交回复
热议问题