首页 > 解决方案 > Java 8:列出来自多个路径的文件

问题描述

如何在 Java 8 中从多个路径搜索文件。这些不是子/兄弟目录。例如,如果我想在路径中搜索 json 文件,我有:

try (Stream<Path> stream = Files.find(Paths.get(path), Integer.MAX_VALUE, (p, attrs) -> attrs.isRegularFile() && p.toString().endsWith(".json"))) {
  stream.map((p) -> p.name).forEach(System.out::println);
}

有没有更好的方法来搜索多个路径?还是我必须为多个路径运行相同的代码?

标签: javafilejava-8

解决方案


是的,你可以做到。假设你有一个对象的路径ListString你可以这样做,

List<String> paths = ...;

paths.stream().map(path -> {
    try (Stream<Path> stream = Files.list(Paths.get(path))) {
        return stream.filter(p -> !p.toFile().isDirectory()).filter(p -> p.toString().endsWith(".json"))
                .map(Path::toString).collect(Collectors.joining("\n"));
    } catch (IOException e) {
        // Log your ERROR here.
        e.printStackTrace();
    }
    return "";
}).forEach(System.out::println);

如果您需要摆脱换行符,那么也可以这样做。

paths.stream().map(path -> {
    try (Stream<Path> stream = Files.walk(Paths.get(path))) {
        return stream.filter(p -> !p.toFile().isDirectory()).filter(p -> p.toString().endsWith(".json"))
                .map(Path::toString).collect(Collectors.toList());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return Collections.emptyList();
}).flatMap(List::stream).forEach(System.out::println);

在这里,您将.json每个路径的所有文件名放入 a中,然后在打印之前List将它们展平stream为对象的平面。String请注意,此方法中涉及的附加步骤是flatMap.


推荐阅读