Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

java - 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 :

-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.

question from:https://stackoverflow.com/questions/65941143/how-to-get-all-files-with-xml-extension-placed-in-resources-of-springboot-applic

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit

You can fetch the known directory files and recursively list all the File[] 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 and 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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...