0
votes

I'm working with spring batch 4 (annotation) and have a job with one step which reads an XML file and write to a text file. I used a custom reader and a simple flat writer (spring batch reference), before reading XML. I checked if this XML is a file, and if so I process the transformation from XML to text. But if the file is not valid I return null in the reader.

The problem is that when I return null in the reader, the writer is still working and puts an empty file into the output folder. What is the solution?

@Bean public FlatFileItemWriter itemWriter() {
    return  
        new FlatFileItemWriterBuilder<Foo>()
            .name("itemWriter")
            .resource(new FileSystemResource("target/test-outputs/output.txt"))
            .lineAggregator(new PassThroughLineAggregator<>())
            .build();
}
1

1 Answers

1
votes

The problem is that when I return null in the reader, the writer is still working and puts an empty file into the output folder. What is the solution?

You can set the shouldDeleteIfEmpty on the FlatFileItemWriter and the output file will be deleted if it is empty. More details on this here: https://docs.spring.io/spring-batch/4.0.x/api/org/springframework/batch/item/file/builder/FlatFileItemWriterBuilder.html#shouldDeleteIfEmpty-boolean-

But if the file is not valid I return null in the reader.

Returning null means the datasource is valid and is exhausted (and might be empty). For an invalid datasource, I would throw an exception and fail the step instead. Another solution is to use the NoWorkFoundStepExecutionListener to fail the step if no work is found. More details about this listener here: https://docs.spring.io/spring-batch/4.0.x/reference/html/common-patterns.html#handlingStepCompletionWhenNoInputIsFound