20

我想使用 Java 8 递归地列出我计算机上的所有文件。

Java 8 提供了listFiles一种返回所有文件和目录但没有递归的方法。如何使用它来获取文件的完整递归列表(不使用变异集合)?

我已经尝试了下面的代码,但它只深入了一层:

static Function<Path, Stream<Path>> listFiles = p -> {
    if (p.toFile().isDirectory()) {
        try { return Files.list(p); }
        catch (Exception e) { return Stream.empty(); }
    } else {
        return Stream.of(p);
    }
};

public static void main(String[] args) throws IOException {
    Path root = Paths.get("C:/temp/");
    Files.list(root).flatMap(listFiles).forEach(System.out::println);
}

并且 usingreturn Files.list(p).flatMap(listFiles);不编译(不知道为什么)......

注意:我对涉及 FileVisitor 或外部库的解决方案不感兴趣。

4

2 回答 2

21

通过递归遍历文件系统来生成路径流的新 API 是Files.walk.

如果您真的想递归地生成流(不一定要遍历文件树,但我将继续使用它作为示例),使用方法引用完成递归可能会更直接一些:

class RecursiveStream {
    static Stream<Path> listFiles(Path path) {
        if (Files.isDirectory(path)) {
            try { return Files.list(path).flatMap(RecursiveStream::listFiles); }
            catch (Exception e) { return Stream.empty(); }
        } else {
            return Stream.of(path);
        }
    }

    public static void main(String[] args) {
        listFiles(Paths.get(".")).forEach(System.out::println);
    }
}

方法引用对于将具有相同“形状”(参数和返回类型)作为功能接口的命名方法改编为该功能接口非常有用。这也避免了将 lambda 存储在实例或静态变量中并递归调用自身的潜在初始化循环。

于 2014-02-08T21:31:44.277 回答
4

显然不可能通过方法引用来引用该函数定义中的函数,但它适用于 lambda。

所以在函数中,return Files.list(p).flatMap(listFiles);不编译而是编译return Files.list(p).flatMap(q -> listFiles.apply(q));

这将递归打印给定文件夹中的所有文件:

static final Function<Path, Stream<Path>> listFiles = p -> {
    if (p.toFile().isDirectory()) {
        try { return Files.list(p).flatMap(q -> listFiles.apply(q)); }
        catch (Exception e) { return Stream.empty(); }
    } else {
        return Stream.of(p);
    }
};

public static void main(String[] args) throws IOException {
    Path root = Paths.get("C:/temp/");
    Files.list(root).flatMap(listFiles).forEach(System.out::println);
}

但正如所指出的,这是不必要的:

Files.walk(root).forEach(System.out::println);

做同样的事情...

于 2014-02-08T13:54:29.273 回答