How to read from files with Files.lines(…).forEach(…)?

前端 未结 5 565
不思量自难忘°
不思量自难忘° 2020-12-03 07:53

I\'m currently trying to read lines from a text only file that I have. I found on another stackoverflow(Reading a plain text file in Java) that you can use Files.lines(..).f

5条回答
  •  盖世英雄少女心
    2020-12-03 08:32

    Avoid returning a list with:

    List lines = Files.readAllLines(path); //WARN
    

    Be aware that the entire file is read when Files::readAllLines is called, with the resulting String array storing all of the contents of the file in memory at once. Therefore, if the file is significantly large, you may encounter an OutOfMemoryError trying to load all of it into memory.

    Use stream instead: Use Files.lines(Path) method that returns a Stream object and does not suffer from this same issue. The contents of the file are read and processed lazily, which means that only a small portion of the file is stored in memory at any given time.

    Files.lines(path).forEach(System.out::println);
    

提交回复
热议问题