Java 如何使用 Files.lines(...).forEach(...) 从文件中读取?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23276407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:37:19  来源:igfitidea点击:

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

javafileforeachfilereaderline-by-line

提问by user3570058

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(..).forEach(..) However I can't actually figure out how to use the for each function to read line by line text, Anyone know where to look for that or how to do so?

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

回答by Sotirios Delimanolis

Files.lines(Path)expects a Pathargument and returns a Stream<String>. Stream#forEach(Consumer)expects a Consumerargument. So invoke the method, passing it a Consumer. That object will have to be implemented to do what you want for each line.

Files.lines(Path)需要一个Path参数并返回一个Stream<String>. Stream#forEach(Consumer)期待Consumer争论。因此调用该方法,将其传递给Consumer. 必须实现该对象才能为每一行执行您想要的操作。

This is Java 8, so you can use lambda expressions or method references to provide a Consumerargument.

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

回答by pardeep131085

Sample content of test.txt

test.txt 的示例内容

Hello
Stack
Over
Flow
com

Code to read from this text file using lines()and forEach()methods.

使用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<String> lines = Files.lines(path)) {
            lines.forEach(s -> System.out.println(s));
        } catch (IOException ex) {
          // do something or re-throw...
        }
    }
}

回答by Arpit Aggarwal

With Java 8, if file exists in a classpath:

使用Java 8,如果文件存在于 a 中classpath

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

回答by Kumar Abhishek

I have created a sample , you can use the Stream to filter/

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

public class ReadFileLines {
    public static void main(String[] args) throws IOException {
        Stream<String> 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());
    }
}

Sample input.txt.

示例输入.txt。

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

回答by Imar

Avoid returning a list with:

避免返回带有以下内容的列表:

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

Be aware that the entire file is read when Files::readAllLinesis 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 OutOfMemoryErrortrying to load all of it into memory.

请注意,Files::readAllLines调用时会读取整个文件,生成的 String 数组一次将文件的所有内容存储在内存中。因此,如果文件非常大,您可能会遇到OutOfMemoryError试图将其全部加载到内存中的情况。

Use stream instead: Use Files.lines(Path)method that returns a Stream<String>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)返回Stream<String>对象且不会遇到相同问题的方法。文件的内容被惰性读取和处理,这意味着在任何给定时间只有一小部分文件存储在内存中。

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