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

时间:2015-07-29 12:33:30

标签: java spring spring-batch

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

以下操作不起作用,因为委托将尝试打开名为*.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>

4 个答案:

答案 0 :(得分:9)

我认为你应该使用PathMatchingResourcePatternResolver

答案 1 :(得分:8)

像这样使用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 :(得分:2)

绝对文件路径

中读取多个文件
 @Bean
      public MultiResourceItemReader<POJO> multiResourceItemReader() {
        MultiResourceItemReader<POJO> resourceItemReader = new MultiResourceItemReader<POJO>();
            ClassLoader cl = this.getClass().getClassLoader();
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);

        Resource[] resources = resolver.getResources("file:" + filePath );
        resourceItemReader.setResources(resources);
        resourceItemReader.setDelegate(reader());
        return resourceItemReader;
      }

      @Bean
      public FlatFileItemReader<POJO> reader() {
        FlatFileItemReader<POJO> reader = new FlatFileItemReader<POJO>();
        reader.setLineMapper(new DefaultLineMapper() {{
          setLineTokenizer(new DelimitedLineTokenizer() {{
            setNames(new String[]{"id1", "POJO"});
          }});
          setFieldSetMapper(new BeanWrapperFieldSetMapper<POJO>() {{
            setTargetType(POJO.class);
          }});
        }});
        return reader;
      }

答案 3 :(得分:1)

或者,@ Value批注可用于让ResourceArrayPropertyEditor将字符串转换为Resource []。

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