Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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>();
        lineAggregator.setDelimiter(",");
        lineAggregator.setFieldExtractor(fieldExtractor);
        
        FlatFileItemWriter<User> writer = new FlatFileItemWriter<User>(...