递归流 [英] Recursive stream
问题描述
我想使用Java 8递归列出计算机上的所有文件。
I want to list all the files on my computer recursively using Java 8.
Java 8提供 listFiles
返回所有文件和目录但没有递归的方法。如何使用它来获取完整的递归文件列表(不使用变异集合)?
Java 8 provides a listFiles
method that returns all the files and directories but without recursion. How can I use it to get a full recursive list of files (without using a mutating collection)?
我已经尝试了下面的代码,但它只有一个深度:
I've tried the code below but it only goes one level deep:
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);
}
并使用返回Files.list(p)。 flatMap(listFiles);
无法编译(不确定原因)......
And using return Files.list(p).flatMap(listFiles);
does not compile (not sure why)...
注意:我对涉及FileVisitors或外部的解决方案不感兴趣库。
Note: I am not interested in solutions involving FileVisitors or external libraries.
推荐答案
通过递归遍历文件系统生成路径流的新API是 Files。步行
。
A new API to generate a stream of Paths by walking the filesystem recursively is Files.walk
.
如果你真的想递归生成一个流(不一定要走文件树,但我会继续使用它作为一个例如,使用方法引用完成递归可能会更直接:
If you really want to generate a stream recursively (not necessarily walking the file tree, but I'll continue using that as an example), it might be a bit more straightforward to accomplish the recursion using method references:
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);
}
}
方法参考对于调整a非常有用具有相同形状(参数和返回类型)的命名方法,作为该功能接口的功能接口。这也避免了在实例或静态变量中存储lambda并以递归方式调用自身的潜在初始化循环。
Method references turn out to be quite useful for adapting a named method that has the same "shape" (arguments and return type) as a functional interface to that functional interface. This also avoids the potential initialization circularity with storing a lambda in an instance or static variable and calling itself recursively.
这篇关于递归流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!