如何使用Files.lines(…)。forEach(…)读取文件?

我目前正在尝试从我拥有的纯文本文件中读取行。 我发现另一个stackoverflow( 用Java读取纯文本文件 ),你可以使用Files.lines(..)。forEach(..)但是我实际上无法弄清楚如何使用for each函数来读取line by行文本,任何人都知道在哪里寻找或如何这样做?

test.txt的示例内容

 Hello Stack Over Flow com 

使用lines()forEach()方法从此文本文件中读取的代码。

 import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; public class FileLambda { public static void main(String JavaLatte[]) { Path path = Paths.get("/root/test.txt"); try (Stream lines = Files.lines(path)) { lines.forEach(s -> System.out.println(s)); } catch (IOException ex) { // do something or re-throw... } } } 

对于Java 8 ,如果文件存在于classpath

 Files.lines(Paths.get(ClassLoader.getSystemResource("input.txt") .toURI())).forEach(System.out::println); 

Files.lines(Path)需要Path参数并返回StreamStream#forEach(Consumer)需要一个Consumer参数。 因此,调用该方法,将其传递给Consumer 。 必须实现该对象以执行每行所需的操作。

这是Java 8,因此您可以使用lambda表达式或方法引用来提供Consumer参数。

我创建了一个示例,可以使用Stream来过滤/

 public class ReadFileLines { public static void main(String[] args) throws IOException { Stream lines = Files.lines(Paths.get("C:/SelfStudy/Input.txt")); // System.out.println(lines.filter(str -> str.contains("SELECT")).count()); //Stream gets closed once you have run the count method. System.out.println(lines.parallel().filter(str -> str.contains("Delete")).count()); } } 

示例input.txt。

 SELECT Every thing Delete Every thing Delete Every thing Delete Every thing Delete Every thing Delete Every thing Delete Every thing 

避免返回如下列表:

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

请注意,调用readAllLines()时会读取整个文件,生成的String数组会立即将该文件的所有内容存储在内存中。 因此,如果文件非常大,您可能会遇到尝试将所有文​​件加载到内存中的OutOfMemoryError。

请改用流:使用Files.lines(Path)方法返回Stream对象,并且不会遇到同样的问题。 懒惰地读取和处理文件的内容,这意味着在任何给定时间只有一小部分文件存储在存储器中。

Files.lines(路径).forEach(的System.out ::的println);