繁体   English   中英

如何获取springboot应用程序资源中所有扩展名为xml的文件?

[英]How to get all files with xml extension placed in resources of springboot application?

我有一个 spring-boot 应用程序,我想收集所有 XML 文件,这些文件位于/src/main/resources目录中,其结构如下所示:

-resources
   -files
      -dir1
        -dir11
           a.xml
           b.xml
      -dir2
        -dir21
          c.xml
      -dir3
        -dir31
          d.xml 

I have tried few solutions like using ResourceUtils.getFile , ClassPathResource , ResourcePatternResolver , ClassLoader but these only work when I am running my application in IDE and dont work if I package my application as jar and deploy it. 我得到以下异常

java.io.FileNotFoundException: class path resource [files] cannot be resolved to absolute file path because it does not reside in the file system:

目录名(dir1、dir11、dir2 等)和文件名(a.xml、b.xml)不是固定的,因此在代码中是未知的。

这些目录和文件可以有任何名称。

resources/files是唯一已知的目录,我想收集此目录及其子目录中的所有 xml 文件。

我已经尝试了几乎所有在网上找到的解决方案,但似乎对我的用例没有任何作用。

如何才能做到这一点? 提前致谢。

编辑

您可以获取已知目录files并递归列出所有File[]对象。

如果您使用org.apache.commons.io.FileUtils.listFiles(File directory, String[] extensions, boolean recursive);

我创建了一个帮助器 function 如下所示来包装String.formatclasspath:

public static File getResourceAsFile(String relativeFilePath) throws FileNotFoundException {
        return ResourceUtils.getFile(String.format("classpath:%s",relativeFilePath));

}

并使用它,

String relativeFilePath ="files";

File file =getResourceAsFile(relativeFilePath);


Collection<File> files=FileUtils.listFiles(file,null,true); //


如果您想读取所有xml文件,则将第二个参数传递为

Collection<File> files=FileUtils.listFiles(file,new String[]{"xml"},true);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM