Over a million developers have joined DZone.

Spring Batch FlatFileItemWriter Hacking

Code snippets demonstrating how to use the FlatFileItemWriter class in Spring.

· Java Zone

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

In this article I explained how to use FlatFileItemWriter class to write a flat file without using a complete Spring batch flow.

Person.java domain object

package com.flatfile.domain;

public class Person {

   private final String firstName;
   private final String lastName;
   private final String middleName;

   public Person(String fn,String ln,String mn){
   public String getFirstName() {
      return firstName;

   public String getLastName() {
      return lastName;

   public String getMiddleName() {
      return middleName;

   public String toString() {
      return firstName+"	"+lastName+"	"+middleName;



This is a builder pattern for constructing a Person object:

package com.flatfile.domain;

public final class PersonBuilder {

   private  String firstName;
   private  String lastName;
   private  String middleName;

   private PersonBuilder() {}
   public static PersonBuilder newBuilder() {
      return new PersonBuilder();

   public PersonBuilder firstName(String fn) {
      return this;
   public PersonBuilder lastName(String ln) {
      return this;
   public PersonBuilder middleName(String mn) {
      return this;
   public Person build() {
      return new Person(firstName,lastName,middleName);


This is a class for writing header into flat file. For more details, see the file-writer.xml Spring bean context file:

package com.flatfile.callback;

import java.io.IOException;
import java.io.Writer;

import org.springframework.batch.item.file.FlatFileHeaderCallback;
import org.springframework.batch.item.file.LineCallbackHandler;
import org.springframework.util.Assert;

public class HeaderCopyCallback implements LineCallbackHandler, FlatFileHeaderCallback {

   private String header="";

   public HeaderCopyCallback(String columns) {
   public void writeHeader(Writer writer) throws IOException {

   public void handleLine(String line) {

      this.header = line;



This is an interface for callback. See the implementation in FlatFileWriterTemplate.java, FileWriter.java class.

package com.flatfile.callback;

import java.util.List;

public interface FlatFileRecordsWriter<T> {

   List<? extends T> doWrite();


Basically this template class is wrapping FlatFileItemWriter reference and also handling file opening,writing, and closing. This class is similar like JdbcTemplate

import java.util.List;

import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.file.FlatFileItemWriter;

import com.flatfile.domain.Person;

public class FlatFileWriterTemplate {

   private final FlatFileItemWriter<Person> flatFileItemWriter;

   public FlatFileWriterTemplate(final FlatFileItemWriter<Person> flatFileItemWriter) {

   public  void writeAll(FlatFileRecordsWriter<? extends Person> fwc) throws Exception {
       try {
          List<? extends Person> returnValue = fwc.doWrite();
          flatFileItemWriter.open(new ExecutionContext());
       finally {




FlatFileWriter class has two methods: write and writeAll.  The first write method takes one argument, i.e. a Person object, and writes it to a flat file. Another writeAll method takes the list of Person objects as an argument and writes them into a flat file.

package com.flatfile.manager;

import java.util.Arrays;
import java.util.List;

import com.flatfile.callback.FlatFileRecordsWriter;
import com.flatfile.callback.FlatFileWriterTemplate;
import com.flatfile.domain.Person;

public class FlatFileWriter {

   private final  FlatFileWriterTemplate flatFileWriterTemplate;

   public FlatFileWriter(FlatFileWriterTemplate flatFileWriterTemplate) {

   public void write(final Person person) throws Exception {
     flatFileWriterTemplate.writeAll(new FlatFileRecordsWriter<Person>() {
      public List<? extends Person> doWrite() {
         return Arrays.asList(person);


   public void writeAll(final List<? extends Person> person) throws Exception {
      flatFileWriterTemplate.writeAll(new FlatFileRecordsWriter<Person>() {
       public List<? extends Person> doWrite() {
          return person;




The below JUnit class shows how to use to FlatFileWriter's write and writeAll methods. 

package com.flatfile.writer;

import java.util.Arrays;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.flatfile.domain.Person;
import com.flatfile.domain.PersonBuilder;
import com.flatfile.manager.FlatFileWriter;

public class FlatFileWriterTest {

   private FlatFileWriter writer;

   public void writeSinglePerson() throws Exception {

      Person person = PersonBuilder.newBuilder()


   public void writeMultiplePersonRecords() throws Exception {

      Person person1 = PersonBuilder.newBuilder()

      Person person2 = PersonBuilder.newBuilder()

      Person person3 = PersonBuilder.newBuilder()




<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd

<bean id="flatFileWriter" class="org.springframework.batch.item.file.FlatFileItemWriter">
<property name="resource" ref="outputResource" />
<property name="appendAllowed" value="true" />
<property name="lineAggregator">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
<property name="delimiter" value=";"/>
<property name="fieldExtractor">
<bean  class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<property name="names" value="firstName,lastName,middleName" />
<property name="headerCallback" ref="headerCopier" />

<bean id="headerCopier"class="com.writer.HeaderCopyCallback" >
<constructor-arg value="FirstName;LastName;MiddleName"></constructor-arg>

<bean id="outputResource" class="org.springframework.core.io.ClassPathResource">
<constructor-arg type="java.lang.String"
value="data/headerSample/person.txt" />

<bean id="writerManager" class="com.flatfile.manager.FlatFileWriter">
<bean class="com.flatfile.callback.FlatFileWriterTemplate">
<constructor-arg ref="flatFileWriter"></constructor-arg>


This class is an item writer that writes data to a file or stream. The writer also provides a restart. The location of the output file is defined by a Resource and must represent a writable file. Uses buffered writers to improve performance.

The implementation is not thread-safe.  (Spring doc)


LineAggregator implementation that converts an object into a delimited list of strings. The default delimiter is a comma (from Spring doc).


This is a field extractor for a Java bean. Given an array of property names, it will reflectively call getters on the item and return an array of all the values(from Spring docs). It extract Person's firstName,lastName, and middleName values and return to FlatFileItemWriter.


See the HeaderCopyCallback.java above for implementation. The bean provides header columns for the flat file.


ClasspathResource-> Resource implementation for class path resources. Uses either a given ClassLoader or a given Class for loading resources (from Spring doc). This bean points to the flat file location after writing header and records.


This bean has a FlatFileWriterTempate reference and the client is going to invoke a writerManager.write/writeAll method. See the above class FlatFileWriter.java and FlatFilwWriterTest.java for example.

For the complete code please visit this link: https://github.com/upenderc/flatfile-hack

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

spring batch

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}