Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read all files in a folder with spring-batch and MultiResourceItemReader?

I want to configure spring-batch to read all csv files inside a specific folder sequentially.

The following does not work because the delegate will try to open a file named *.csv, which of course is invalid. What do I have to change here?

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

The equivalent xml configuration would be written as follows, how could I rewrite it to java only config?

<bean id="reader" class="org.springframework.batch.item.file.MultiResourceItemReader">
        <property name="resources" value="/mypfolder/*.csv"/>
        <property name="delegate" ref="flatFileItemReader"/>
</bean>
like image 625
membersound Avatar asked Jul 29 '15 12:07

membersound


People also ask

How do I read multiple files in Spring Batch?

You need to use MultiResourceItemReader to read lines from CSV file. It reads items from multiple resources sequentially. FlatFileItemReader<Employee> reader = new FlatFileItemReader<Employee>(); //Set number of lines to skips.

How do I read multiple CSV files in spring boot?

The csv file can be read in the spring boot batch application using the ItemReader implemented java class FlatFileItemReader. In the spring boot batch application, the FlatFileItemReader class reads the csv file data and converts it to an object.

What is ItemReader in Spring Batch?

ItemReader. It is the entity of a step (of a batch process) which reads data. An ItemReader reads one item a time. Spring Batch provides an Interface ItemReader. All the readers implement this interface.


2 Answers

Use PathMatchingResourcePatternResolver like this.

@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;
}
like image 144
Tharindu Jayasuriya Avatar answered Oct 12 '22 21:10

Tharindu Jayasuriya


I think you should use a PathMatchingResourcePatternResolver.

like image 10
Luca Basso Ricci Avatar answered Oct 12 '22 19:10

Luca Basso Ricci