In this post, I will explain how to write the employee objects created in the reading process to a file.
To write the list of employee records in batches, we need to create an instance of org.springframework.batch.item.file.FlatFileItemWriter.
It takes two information
1) the resource file where the information has to be written
2) An instance of LineAggregator which converts the objects to string format
Below is xml snippet
<bean id="writer" class="org.springframework.batch.item.file.FlatFileItemWriter">
<property name="resource" value="file:FileOutput.txt"/>
<property name="lineAggregator">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
...
</bean>
</property>
</bean>
In the above code we are using an instance of DelimitedLineAggregator, which converts the object to string form, with field values separated by comma.
A comma is default delimiter used by DelimitedLineAggregator but we can change it.
An instance of DelimitedLineAggregator requires an instance of FieldExtractor. The purpose of the FieldExtractor is to get an array of values.
The array of values are given to DelimitedLineAggregator which converts them to string of field values separated by comma.
Below is the xml snippet
<bean id="writer" class="org.springframework.batch.item.file.FlatFileItemWriter">
<property name="resource" value="file:FileOutput.txt"/>
<property name="lineAggregator">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
<property name="fieldExtractor">
<bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
<property name="names" value="id,name,status,salary"/>
</bean>
</property>
</bean>
</property>
</bean>
In the above code snippet we used an instance of BeanWrapperFieldExtractor.
The BeanWrapperFieldExtractor takes a list of property names which have to included in the string format. Call these properties on the employee object reflectively and convert them to array of values.
In the next post I will explain how to combine the reader and writer in a job and how to run the job.