Generating a CSV file
Write a CSV file as part of a read/process/write step.
Getting ready
We will generate a CSV file from User
objects. Make sure that the User
class exists:
public class User { private String firstName; private int age;
How to do it…
Use FlatFileItemWriter
provided by Spring Batch:
Add a
writer()
method that will get the fields of aUser
object, build a comma-separated line with them, and write the line to a CSV file:@Bean @StepScope public FlatFileItemWriter<User> writer(@Value("#{jobParameters[fileOut]}") String csvFilePath) { BeanWrapperFieldExtractor<User> fieldExtractor = new BeanWrapperFieldExtractor<User>(); fieldExtractor.setNames(new String[]{"firstName","age"}); DelimitedLineAggregator<User> lineAggregator = new DelimitedLineAggregator<User>(); lineAggregator.setDelimiter(","); lineAggregator.setFieldExtractor(fieldExtractor); FlatFileItemWriter<User> writer = new FlatFileItemWriter<User>(...