没有使用Spring PathMatchingResourcePatternResolver查找资源

时间:2018-02-14 15:50:11

标签: java spring spring-batch spring-io

   @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;
    }

即使位置中有文件,我也无法获取资源。在前面的步骤中,文件被复制,然后我尝试使用PathMatchingResourcePatternResolver查找文件。我在控制台上打印了以下内容:

 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.

我可以看到locationPattern的构造正确。

filePathfilePatternapplication.properties文件中如下所示:

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

positionFile.patternName=PositionFile

2 个答案:

答案 0 :(得分:0)

您未在 PathMatchingResourcePatternResolver

中设置 ClassLoader
ClassLoader cl = this.getClass().getClassLoader();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);

答案 1 :(得分:0)

我遇到了同样的问题,经过一些挖掘,似乎 PathMatchingResourcePatternResolver 有时会遇到用反斜杠解决的问题,有时工作正常

为了提高可靠性,我解决了用正斜杠替换所有反斜杠的问题

试试这个:

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

注意:Windows 平台上的 File.separator 也会出现问题