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:

  1. Add a writer() method that will get the fields of a User 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>(); ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.