[英]How to get all files with xml extension placed in resources of springboot application?
I have a spring-boot application and I want to collect all XML files which are placed in the /src/main/resources
directory which follows a structure as given below:我有一个 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. 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. I get below exception我得到以下异常
java.io.FileNotFoundException: class path resource [files] cannot be resolved to absolute file path because it does not reside in the file system:
Directory names (dir1, dir11, dir2 etc) and file names (a.xml, b.xml) are not fixed and so not known in code.目录名(dir1、dir11、dir2 等)和文件名(a.xml、b.xml)不是固定的,因此在代码中是未知的。
These directories and files can have any names.这些目录和文件可以有任何名称。
resources/files
is the only known directory and I want to collect all xml files inside this directory and its subdirectory. resources/files
是唯一已知的目录,我想收集此目录及其子目录中的所有 xml 文件。
I have tried almost all solutions found on net, but nothing seems to work for my use-case.我已经尝试了几乎所有在网上找到的解决方案,但似乎对我的用例没有任何作用。
How can this be done?如何才能做到这一点? Thanks in advance.
提前致谢。
Edit编辑
You can fetch the known directory files
and recursively list all the File[]
objects.您可以获取已知目录
files
并递归列出所有File[]
对象。
It would be easier if you user org.apache.commons.io.FileUtils.listFiles(File directory, String[] extensions, boolean recursive);
如果您使用
org.apache.commons.io.FileUtils.listFiles(File directory, String[] extensions, boolean recursive);
I've created a helper function like below to wrap the logic of String.format
and classpath:
我创建了一个帮助器 function 如下所示来包装
String.format
和classpath:
public static File getResourceAsFile(String relativeFilePath) throws FileNotFoundException {
return ResourceUtils.getFile(String.format("classpath:%s",relativeFilePath));
}
And to use it,并使用它,
String relativeFilePath ="files";
File file =getResourceAsFile(relativeFilePath);
Collection<File> files=FileUtils.listFiles(file,null,true); //
And if you want to read all the xml
files, then pass second parameter as如果您想读取所有
xml
文件,则将第二个参数传递为
Collection<File> files=FileUtils.listFiles(file,new String[]{"xml"},true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.