如何使用spring-batch和MultiResourceItemReader读取文件夹中的所有文件?

2022-09-04 06:19:05

我想配置为按顺序读取特定文件夹中的所有文件。spring-batchcsv

以下操作不起作用,因为委托将尝试打开一个名为 的文件,该文件当然是无效的。我必须在这里更改什么?*.csv

    @Bean
    public ItemReader<String> reader() {
        MultiResourceItemReader<String> reader = new MultiResourceItemReader<>();
        reader.setResources(new Resource[] {new FileSystemResource("/myfolder/*.csv")});
        reader.setDelegate(new FlatFileItemReader<>(..));
        return reader;
}

等效的xml配置将编写如下,我该如何将其重写为仅java配置?

<bean id="reader" class="org.springframework.batch.item.file.MultiResourceItemReader">
        <property name="resources" value="/mypfolder/*.csv"/>
        <property name="delegate" ref="flatFileItemReader"/>
</bean>

答案 1

像这样使用 PathMatchingResourcePatternResolver。

@Bean
public ItemReader<String> reader() {
    Resource[] resources = null;
    ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();   
    try {
        resources = patternResolver.getResources("/myfolder/*.csv");
    } catch (IOException e) {
        e.printStackTrace();
    }
    MultiResourceItemReader<String> reader = new MultiResourceItemReader<>();
    reader.setResources(resources);
    reader.setDelegate(new FlatFileItemReader<>(..));
    return reader;
}

答案 2

我认为你应该使用PathMatchingResourcePatternResolver