【问题标题】:How to get all files in directory in the classpath如何获取类路径中目录中的所有文件
【发布时间】:2016-02-20 09:13:00
【问题描述】:

有没有办法使用ResourceLoader 获取jar 目录中的“子资源”列表?

例如,给定来源

src/main/resources/mydir/myfile1.txt
src/main/resources/mydir/myfile2.txt

并使用

@Autowired
private ResourceLoader resourceLoader;

我可以进入目录

Resource dir = resourceLoader.getResource("classpath:mydir")
dir.exists() // true

但不是目录中的文件。如果我能拿到文件,我可以打电话给dir.getFile().listFiles(),但是

dir.getFile() // explodes with FileNotFoundException

但我找不到获取“子”资源的方法。

【问题讨论】:

    标签: spring-boot classpath embedded-resource


    【解决方案1】:

    您可以使用ResourcePatternResolver 来获取与特定模式匹配的所有资源。例如:

    Resource[] resources = resourcePatternResolver.getResources("/mydir/*.txt")
    

    您可以像ResourceLoader 一样注入ResourcePatternResolver

    【讨论】:

    • 好的,但我不知道我会在那里找到什么。也许"/mydir/*" 与您的代码。我最终得到了它与PathMatchingResourcePatternResolver
    • 资源包是什么?我找不到任何属于 Spring 的具有该名称的类。
    • 对不起,这是答案中的错字。我现在已经修好了。
    【解决方案2】:

    基于Bohemian's 和另一个answer,我使用以下方法获取资源中目录和子目录下所有 YAML 的输入流(注意传递的路径不以/ 开头):

    private static Stream<InputStream> getInputStreamsFromClasspath(
            String path,
            PathMatchingResourcePatternResolver resolver
    ) {
        try {
            return Arrays.stream(resolver.getResources("/" + path + "/**/*.yaml"))
                    .filter(Resource::exists)
                    .map(resource -> {
                        try {
                            return resource.getInputStream();
                        } catch (IOException e) {
                            return null;
                        }
                    })
                    .filter(Objects::nonNull);
        } catch (IOException e) {
            logger.error("Failed to get definitions from directory {}", path, e);
            return Stream.of();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-18
      • 2019-05-08
      • 2012-04-06
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多