How can I read a large text file line by line using Java?

前端 未结 21 2389
心在旅途
心在旅途 2020-11-21 05:48

I need to read a large text file of around 5-6 GB line by line using Java.

How can I do this quickly?

21条回答
  •  遇见更好的自我
    2020-11-21 06:26

    By using the org.apache.commons.io package, it gave more performance, especially in legacy code which uses Java 6 and below.

    Java 7 has a better API with fewer exceptions handling and more useful methods:

    LineIterator lineIterator = null;
    try {
        lineIterator = FileUtils.lineIterator(new File("/home/username/m.log"), "windows-1256"); // The second parameter is optionnal
        while (lineIterator.hasNext()) {
            String currentLine = lineIterator.next();
            // Some operation
        }
    }
    finally {
        LineIterator.closeQuietly(lineIterator);
    }
    

    Maven

    
    
        commons-io
        commons-io
        2.6
    
    

提交回复
热议问题