Not finding resources with Spring PathMatchingResourcePatternResolver

1.5k Views Asked by At
   @Bean
    @StepScope
    public MultiResourceItemReader<PosRow> multiResourceItemReader() {
        MultiResourceItemReader<PosRow> resourceItemReader = new MultiResourceItemReader<>();
        Resource[] resources = new Resource[0];
        String path = "file:" + filePath + File.separator + filePattern + "*";
        log.info("Looking for resource files matching {}", path);
        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            resources = resolver.getResources(path);
        } catch (IOException e) {
            log.error("Problem with getting resource files ", e);
        }
        resourceItemReader.setResources(resources);
        resourceItemReader.setDelegate(posRowReader());
        return resourceItemReader;
    }

I am unable to get resources even though there are files in the location. In previous steps, the files get copied over and then I try to look for the files using PathMatchingResourcePatternResolver. I get the following printed on my console:

 c.s.p.p.batch.config.BatchConfiguration  : Looking for resource files matching file:C:\Dev\workspace\batch\src\main\resources\localPath\PositionFile*
o.s.b.item.file.MultiResourceItemReader  : No resources to read. Set strict=true if this should be an error condition.

I can see the locationPattern is correctly constructed.

The filePath and filePattern look like this in application.properties file:

positionFile.local-path=C:\\Dev\\workspace\\batch\\src\\main\\resources\\localPath

positionFile.patternName=PositionFile
2

There are 2 best solutions below

1
Niraj Sonawane On

You are not setting ClassLoader in PathMatchingResourcePatternResolver

ClassLoader cl = this.getClass().getClassLoader();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
0
ACH On

I encountered the same issues and after some digging it seems like PathMatchingResourcePatternResolver sometimes has issues resolving with back slashes, sometimes works fine

For more reliability, I solved the issue replacing all back slashes with forward slashes

try this:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
path = path.replace("\\", "/");
resources = resolver.getResources(path);

NB: Issue also occurs with File.separator on Windows platform