java - 如何使用 Streams 从目录中逐行读取所有文件?

标签 java java-stream

我有一个名为 Files 的目录,它有很多文件。我想逐行读取这些文件并将它们存储在 List<List<String>> .

./Files
 ../1.txt
 ../2.txt
 ../3.txt
 ..
 ..

事情就是这样。

private List<List<String>> records = new ArrayList<>();

List<Path> filesInFolder = Files.list(Paths.get("input"))
                .filter(Files::isRegularFile)
                .collect(Collectors.toList());

records = Files.lines(Paths.get("input/1.txt"))
                .map(row -> Arrays.asList(row.split(space)))
                .collect(Collectors.toList());

最佳答案

逻辑基本上是这样的

List<List<String>> records = Files.list(Paths.get("input"))
    .filter(Files::isRegularFile)
    .flatMap(path -> Files.lines(path)
        .map(row -> Arrays.asList(row.split(" "))))
    .collect(Collectors.toList());

但是您需要捕获 Files.lines 可能引发的 IOException。此外,应关闭Files.list返回的流,以尽快释放相关资源。

List<List<String>> records; // don't pre-initialize
try(Stream<Path> files = Files.list(Paths.get("input"))) {
    records = files.filter(Files::isRegularFile)
        .flatMap(path -> {
            try {
                return Files.lines(path)
                    .map(row -> Arrays.asList(row.split(" ")));
            } catch (IOException ex) { throw new UncheckedIOException(ex); }
        })
        .collect(Collectors.toList());
}
catch(IOException|UncheckedIOException ex) {
    // log the error

    // and if you want a fall-back:
    records = Collections.emptyList();
}

请注意,与 flatMap 一起使用的 Files.lines 返回的流会自动正确关闭,as documented :

Each mapped stream is closed after its contents have been placed into this stream.


也可以将 map 步骤从内部流移动到外部:

List<List<String>> records; // don't pre-initialize
try(Stream<Path> files = Files.list(Paths.get("E:\\projects\\nbMJ\\src\\sub"))) {
    records = files.filter(Files::isRegularFile)
        .flatMap(path -> {
            try { return Files.lines(path); }
            catch (IOException ex) { throw new UncheckedIOException(ex); }
        })
        .map(row -> Arrays.asList(row.split(" ")))
        .collect(Collectors.toList());
}
catch(IOException|UncheckedIOException ex) {
    // log the error

    // and if you want a fall-back:
    records = Collections.emptyList();
}

关于java - 如何使用 Streams 从目录中逐行读取所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65653533/

相关文章:

java - 使用 JMockit 模拟抽象类中的非公共(public)静态方法?

java - 多文件 uploader Java

java - Android - Eclipse 在 SDK 2.2 上使用项目构建/运行速度很慢

java - 在流过滤器中对流使用 Java 过滤器

java - 我应该尽可能使用并行流吗?

java - Spring MVC : Mapping Form input to complex backing object containing HashMap

java - 设备支持删除了在 Playstore Android 上更新应用程序时出现的警告

java - Java 8 Stream 抛出 RuntimeException 时的预期行为是什么?

java - 如何提供 lambda 映射函数作为方法参数?

java - 使用流对 BlockRealMatrix 对象的相应行进行平均