开发者社区> 问答> 正文

如何在Java中“遍历”具有多个文件扩展名的多个目录?

这是我的实际代码,可以正常工作: 字符串sHomeDir是我唯一要开始扫描的文件夹 字符串sExt是唯一要搜索的扩展名

try (Stream<Path> walk = Files.walk(Paths.get(sHomeDir)))
{
    List<String> result = walk.map(x -> x.toString())
        .filter(f -> f.endsWith(sExt)).collect(Collectors.toList());
    ...
} catch (IOException e) {
   e.printStackTrace();
}

是否可以重写该代码以便使用: -多个文件夹进行扫描(带有子树) -多个文件扩展名进行搜索

问题来源:Stack Overflow

展开
收起
montos 2020-03-21 21:39:18 1003 0
1 条回答
写回答
取消 提交回答
  • 要处理多个目录,您可以流式传输它们并将它们平面映射到单个Paths流。要处理多个扩展名,您只需要对照所有扩展名检查文件:

    public static List<String> multiWalk
        (Collection<String> directories, Collection<String> extensions) {
    
        return directories.stream()
                          .flatMap(d -> {
                              try {
                                  return Files.walk(Paths.get(d));
                              } catch (IOException e) {
                                  return Stream.empty();
                              }
                          })
                          .map(Object::toString)
                          .filter(f -> extensions.stream().anyMatch(f::endsWith))
                          .collect(Collectors.toList());
    }
    

    回答来源:Stack Overflow

    2020-03-21 21:39:54
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载