我想使用 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 或外部库的解决方案不感兴趣。