我想使用 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);
}
并且使用 return Files.list(p).flatMap(listFiles);
无法编译(不知道为什么)...
注意:我对涉及 FileVisitor 或外部库的解决方案不感兴趣。
最佳答案
通过递归遍历文件系统来生成路径流的新 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);
}
}
方法引用对于将具有相同“形状”(参数和返回类型)作为函数接口(interface)的命名方法改编为该函数接口(interface)非常有用。这也避免了将 lambda 存储在实例或静态变量中并递归调用自身的潜在初始化循环。
关于java - 递归流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21646683/