Java : Read last n lines of a HUGE file

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

    I found it the simplest way to do by using ReversedLinesFileReader from apache commons-io api. This method will give you the line from bottom to top of a file and you can specify n_lines value to specify the number of line.

    import org.apache.commons.io.input.ReversedLinesFileReader;
    
    
    File file = new File("D:\\file_name.xml");
    int n_lines = 10;
    int counter = 0; 
    ReversedLinesFileReader object = new ReversedLinesFileReader(file);
    while(counter < n_lines) {
        System.out.println(object.readLine());
        counter++;
    }
    

提交回复
热议问题