Java : Read last n lines of a HUGE file

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

    I found RandomAccessFile and other Buffer Reader classes too slow for me. Nothing can be faster than a tail -<#lines>. So this it was the best solution for me.

    public String getLastNLogLines(File file, int nLines) {
        StringBuilder s = new StringBuilder();
        try {
            Process p = Runtime.getRuntime().exec("tail -"+nLines+" "+file);
            java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(p.getInputStream()));
            String line = null;
        //Here we first read the next line into the variable
        //line and then check for the EOF condition, which
        //is the return value of null
        while((line = input.readLine()) != null){
                s.append(line+'\n');
            }
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
        return s.toString();
    }
    

提交回复
热议问题