Search code examples
javaspring-bootfileclasspathresource-loading

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.


Solution

  • 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);