Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-Batch Java Based FileItemWriter for CSV

I have a Spring Batch service containg ItemWriter to write the data to the CSV. I have used the example give by Spring Batch guide. https://spring.io/guides/gs/batch-processing/

I tried to modify the ItemWriter to create the CSV again.

The Problems which I am facing are -

  1. It is not creating the CSV file if it is not present.
  2. If I made it available before hand it is not writing data to it.

@Bean
public ItemWriter<Person> writer(DataSource dataSource) {

FlatFileitemWriter<Person> csvWriter = new FlatFileItemWriter<Person>();
csvWriter.setResource(new ClassPathResource("csv/new-data.csv"));
csvWriter.setShouldDeleteIfExists(true);
DelimitedLineAggregator<Person> lineAggregator = new DelimitedLineAggregator<Person>();
lineAggregator.setDelimiter(","); 

BeanWrapperFieldExtractor<Person> fieldExtractor = new BeanWrapperFieldExtractor<Person>();
String[] names = {"firstName", "lastName"};
fieldExtractor.setNames(names);
lineAggregator.setFieldExtractor(fieldExtractor);
csvWriter.setLineAggregator(lineAggregator);
    return csvWriter;
}

I have gone through various links but they show the example with XML based configuration. How to do it completely in JAVA ?

like image 767
Aditya Khajuria Avatar asked Sep 16 '26 02:09

Aditya Khajuria


1 Answers

You are using a ClassPathResource to write. I'm not sure, but I don't think you can write to a ClassPathResource. Try using a normal FileSystemResource and try again.

Moreover, how do you inject the writer? are you sure that it really is instantiated as spring bean? Why do you have DataSource as a parameter since you don't need a datasource to instantiate a FlatFileItemWriter.

like image 192
Hansjoerg Wingeier Avatar answered Sep 18 '26 21:09

Hansjoerg Wingeier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!