Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Batch FlatFileItemWriter Hacking

DZone's Guide to

Spring Batch FlatFileItemWriter Hacking

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

· Java Zone
Free Resource

Managing a MongoDB deployment? Take a load off and live migrate to MongoDB Atlas, the official automated service, with little to no downtime.

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){
      this.firstName=fn;
      this.lastName=ln;
      this.middleName=mn;
   }
   public String getFirstName() {
      return firstName;
   }

   public String getLastName() {
      return lastName;
   }

   public String getMiddleName() {
      return middleName;
   }

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


}

PersonBuilder.java

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) {
      this.firstName=fn;
      return this;
   }
   public PersonBuilder lastName(String ln) {
      this.lastName=ln;
      return this;
   }
   public PersonBuilder middleName(String mn) {
      this.middleName=mn;
      return this;
   }
   public Person build() {
      return new Person(firstName,lastName,middleName);
   }
}

HeaderCopyCallback.java

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) {
      header=columns;
   }
   @Override
   public void writeHeader(Writer writer) throws IOException {
      writer.write(header);
   }

   @Override
   public void handleLine(String line) {

      Assert.notNull(line);
      this.header = line;
   }

}

FlatFileRecordsWriter.java

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();
}

FlatFileWriterTemplate.java

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) {
      this.flatFileItemWriter=flatFileItemWriter;
   }

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

   }


}

FlatFileWriter.java

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) {
      this.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;
       }
    });

   }

}

FlatFileWriterTest.java

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;

@ContextConfiguration("/file-writer.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class FlatFileWriterTest {

   @Autowired
   private FlatFileWriter writer;

   @Test
   public void writeSinglePerson() throws Exception {

      Person person = PersonBuilder.newBuilder()
             .firstName("Scott")
             .lastName("Miller")
             .middleName("S").build();
         writer.write(person);

   }

   @Test
   public void writeMultiplePersonRecords() throws Exception {

      Person person1 = PersonBuilder.newBuilder()
             .firstName("Robert")
             .lastName("Hope")
             .middleName("C").build();

      Person person2 = PersonBuilder.newBuilder()
            .firstName("James")
            .lastName("Blake")
            .middleName("R").build();

      Person person3 = PersonBuilder.newBuilder()
            .firstName("Larry")
            .lastName("Chen")
            .middleName("S").build();

         writer.writeAll(Arrays.asList(person1,person2,person3));

   }
}

file-writer.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
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
 http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop.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" />
</bean>
</property>
</bean>
</property>
<property name="headerCallback" ref="headerCopier" />
</bean>




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

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

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

flatFileWriter

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)

DelimitedLineAggregator

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

BeanWrapperFieldExtractor

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.

headerCopier

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

outputResource

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.

writerManager

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

MongoDB Atlas is the easiest way to run the fastest-growing database for modern applications — no installation, setup, or configuration required. Easily live migrate an existing workload or start with 512MB of storage for free.

Topics:
spring batch

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}