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 :
-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 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.
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.
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 theFile[]
objects.It would be easier if you user
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
andclasspath:
And to use it,
And if you want to read all the
xml
files, then pass second parameter as