20

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

4

5 回答 5

34

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 args[]) {
        Path path = Paths.of("/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...
        }
    }
    
}
于 2014-04-25T09:24:05.097 回答
8

避免返回包含以下内容的列表:

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

请注意,Files::readAllLines调用时会读取整个文件,生成的字符串数组会立即将文件的所有内容存储在内存中。因此,如果文件非常大,您可能会OutOfMemoryError尝试将其全部加载到内存中。

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

Files.lines(path).forEach(System.out::println);
于 2018-09-26T14:54:21.103 回答
6

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

Files.lines(Paths.get(ClassLoader.getSystemResource("input.txt")
                    .toURI())).forEach(System.out::println);
于 2015-11-17T06:25:11.350 回答
3

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

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

于 2014-04-24T18:12:02.393 回答
2

我创建了一个示例,您可以使用 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());
    }
}

示例 input.txt。

SELECT Every thing
Delete Every thing
Delete Every thing
Delete Every thing
Delete Every thing
Delete Every thing
Delete Every thing
于 2016-04-11T07:48:16.233 回答