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>
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.
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.
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.
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;
}
I think you should use a PathMatchingResourcePatternResolver
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With