gpt4 book ai didi

java - 使用 Java 8 Stream 从根目录递归添加所有文件

转载 作者:搜寻专家 更新时间:2023-10-31 20:00:57 25 4
gpt4 key购买 nike

我有以下递归方法,它只是将给定文件夹中的所有子项添加到列表中:

private List<TemplateFile> readTemplateFiles(String nextTemplateDir, String rootTemplateDir) throws FileNotFoundException {
List<TemplateFile> templateFiles = new ArrayList<>();

for (File file : new File(nextTemplateDir).listFiles()) {
if (!file.isDirectory() && !file.getName().startsWith(".")) {
templateFiles.add(TemplateFile.create(file, rootTemplateDir));
} else if (file.isDirectory()) {
templateFiles.addAll(readTemplateFiles(file.getAbsolutePath(), rootTemplateDir));
}
}

return templateFiles;
}

如何使用新的 Java 8 Stream API 重构此方法?

最佳答案

你可以使用 Files.walk(start, options...) 递归遍历文件树。此方法返回 Stream<Path>由所有 Path 组成从给定的根开始。

Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.

private List<TemplateFile> readTemplateFiles(String nextTemplateDir, String rootTemplateDir) throws FileNotFoundException {
return Files.walk(Paths.get(nextTemplateDir))
.filter(path -> !path.getFileName().startsWith("."))
.map(path -> TemplateFile.create(path.toFile(), rootTemplateDir))
.collect(Collectors.toList());
}

options 当中, 有 FOLLOW_LINKS 这将遵循符号链接(symbolic link)。

关于java - 使用 Java 8 Stream 从根目录递归添加所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34587582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com