Spring-Batch Java Based FileItemWriter for CSV

≯℡__Kan透↙ 提交于 2021-02-08 05:16:51

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/32591542/spring-batch-java-based-fileitemwriter-for-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!