0

I went through Is there a way to override and not execute the headerCallBack in Spring Batch, but still not clear on the solution. I'm using Spring XML based approach in my project.

I'm using ClassifierCompositeItemWriter to segregate the data based on one column and writing it to four different files (off-course unique data in each file).

Sometime I've observed that one file is empty because there is no data to qualify that Classifier, what I want to prevent writing headers into that file and have a pure empty file in case of no data.

<bean id="someCvsWriter" class="org.springframework.batch.item.file.FlatFileItemWriter">
    <property name="resource" value="file:csv/someReport.csv"/>
    <property name="shouldDeleteIfExists" value="true"/>
    <property name="encoding" value="UTF-8"/>
    <property name="lineAggregator" ref="someCustomLineAggregator"/>
    <property name="headerCallback" ref="someReportHeaderCallback" />
</bean>

Header Callback

public class SomeReportFlatFileHeaderCallback implements FlatFileHeaderCallback {

    @Override
    public void writeHeader(Writer writer) throws IOException {
        writer.write("COL1, COL2, COL3");
    }
}

1 Answer 1

0

The FlatFileItemWriter has a property called shouldDeleteIfEmpty, which you can set to true.

So with the additional line

<property name="shouldDeleteIfEmpty" value="true"/>

everything should work as you expect.

See also the Javadoc of the setter: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java#L171

2
  • Thanks, I dont want to delete those files, but I just want to create it empty without headers, is that possible?
    – PAA
    Commented Jul 10 at 5:24
  • I don't think it's possible with an out-of-the-box property. But you can extend AbstractFileItemWriter with a custom implementation that is similar as that for shouldDeleteIfEmpty.
    – Henning
    Commented Jul 10 at 7:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.