java高效读取大文件

BufferReader

我们可以使用 BufferReader#readLine 逐行读取数据。

try (BufferedReader fileBufferReader = new BufferedReader(new FileReader("temp/test.txt"))) { 
    String fileLineContent; 
    while ((fileLineContent = fileBufferReader.readLine()) != null) { 
        // process the line. 
    } 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 



Apache Commons IOCommon-IO

中有一个方法 FileUtils#lineIterator可以实现逐行读取方式,使用代码如下:

 

Stopwatch stopwatch = Stopwatch.createStarted(); 
LineIterator fileContents = FileUtils.lineIterator(new File("temp/test.txt"), StandardCharsets.UTF_8.name()); 
while (fileContents.hasNext()) { 
    fileContents.nextLine(); 
    //  pass 
} 
logMemory(); 
fileContents.close(); 
stopwatch.stop(); 
System.out.println("read all lines spend " + stopwatch.elapsed(TimeUnit.SECONDS) + " s");



Java8 stream

Java8 Files 类新增了一个 lines,可以返回 Stream我们可以逐行处理数据。

 

Stopwatch stopwatch = Stopwatch.createStarted(); 
// lines(Path path, Charset cs) 
try (Stream<String> inputStream = Files.lines(Paths.get("temp/test.txt"), StandardCharsets.UTF_8)) { 
    inputStream 
            .filter(str -> str.length() > 5)// 过滤数据 
            .forEach(o -> { 
                // pass do sample logic 
            }); 
} 
logMemory(); 
stopwatch.stop(); 
System.out.println("read all lines spend " + stopwatch.elapsed(TimeUnit.SECONDS) + " s"); 


使用这个方法有个好处在于,我们可以方便使用 Stream 链式操作,做一些过滤操作。

注意:这里我们使用 try-with-resources 方式,可以安全的确保读取结束,流可以被安全的关闭。

 

Leave a Comment