Java Reference
In-Depth Information
and footer may have been, but no item records were written), and
shouldDeleteIfEmpty
is set to
true
, the
file is deleted on the completion of the step. By default, the file is created and left empty. You can look at
this behavior with the
formatJob
you ran in the previous section. By updating the configuration of
flatFileOutputWriter
to set
shouldDeleteIfEmpty
to
true
as shown in Listing 9-14, you can process an
empty file and see that no output file is left behind.
Listing 9-14.
Configuring
formatJob
to Delete the Output File if No Items Are Written
…
<beans:bean id="flatFileOutputWriter"
class="org.springframework.batch.item.file.FlatFileItemWriter">
<beans:property name="resource" ref="outputFile"/>
<beans:property name="lineAggregator" ref="delimitedLineAggregator"/>
<beans:property name="shouldDeleteIfEmpty" value="true"/>
</beans:bean>
…
If you execute
formatJob
with the updated file and pass it an empty
customer.csv
file as input, no
output is left behind. It's important to note that the file is still created, opened, and closed. In fact, if the
step is configured to write a header and/or footer in the file, that is written as well. However, if the
number of items written to the file is zero, the file is deleted at the end of the step.
The next configuration parameter related to file creation/deletion is the
shouldDeleteIfExists
flag.
This flag, set to
true
by default, deletes a file that has the same name as the output file the step intends to
write to. For example, if you're going to run a job that writes to a file
/output/jobRun.txt
, and that file
already exists when the job starts, Spring Batch deletes the file and creates a new one. If this file exists
and the flag is set to
false
, an
org.springframework.batch.item.ItemStreamException
is thrown when
the step attempts to create the new file. Listing 9-15 shows
formatJob
's
flatFileOutputWriter
configured
to not delete the output file if it exists.
Listing 9-15.
Configuring
formatJob
to Not Delete the Output File if It Already Exists
…
<beans:bean id="flatFileOutputWriter"
class="org.springframework.batch.item.file.FlatFileItemWriter">
<beans:property name="resource" ref="outputFile"/>
<beans:property name="lineAggregator" ref="delimitedLineAggregator"/>
<beans:property name="shouldDeleteIfExists" value="false"/>
</beans:bean>
…
By running the job as it's configured in Listing 9-15, you receive the previously mentioned
ItemStreamException
as shown in Listing 9-16.
Listing 9-16.
Results of a Job that Writes to an Existing File that Shouldn't Be There
2011-03-06 12:32:51,006 DEBUG main
[org.springframework.batch.core.scope.StepScope] - <Creating object in
scope=step, name=scopedTarget.outputFile>
2011-03-06 12:32:51,065 ERROR main
[org.springframework.batch.core.step.AbstractStep] - <Encountered an error
executing the step>