We have a batch job to check DB data.If the data has any problems,it will write something to the output-file.In another way,it will write nothing. BUT,what ever the problem has or not,the output-file will created. And we want it to not create output files when the date is fine.
Here if our xml.
<batch:job id="DEFAULT_JOB_ID">
<batch:step id="step">
<batch:tasklet transaction-manager="transactionManager" start-limit="100">
<batch:chunk reader="dbReader01" processor="testProc" writer="classifierWriter01" commit-interval="100" >
<batch:streams>
<batch:stream ref="fileWriter01"/>
</batch:streams>
</batch:chunk>
<batch:listeners>
<batch:listener ref="defaultChunkListener" />
</batch:listeners>
</batch:tasklet>
</batch:step>
<batch:listeners>
<batch:listener ref="defaultJobExecutionListener" />
</batch:listeners>
</batch:job>
<bean id="classifierWriter01" class="org.springframework.batch.item.support.ClassifierCompositeItemWriter" scope="step">
<property name="classifier">
<bean class="org.springframework.classify.BackToBackPatternClassifier">
<property name="routerDelegate">
<bean class="src.test.DefaultClassifier" />
</property>
<property name="matcherMap">
<util:map id="matcherMap" scope="step">
<!-- FLAG == 0 THEN write something -->
<entry key="0" value-ref="fileWriter01" />
<!-- FLAG == 1 THEN write nothing -->
<entry key="1" value-ref="dummyWriter" />
</util:map>
</property>
</bean>
</property>
</bean>
<bean id="fileWriter01" class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
<property name="encoding" value="UTF-8" />
<property name="resource" value="file:#{jobParameters['outFile']}" />
<property name="appendAllowed" value="false"/>
<property name="shouldDeleteIfExists" value="true"/>
<property name="lineAggregator">
<bean class="src.test.DelimitedLineAggregator">
<property name="delimiter" value="," />
<property name="allEnclosing" value="true" />
<property name="enclosure" value='"' />
<property name="fieldExtractor">
<bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor" >
<property name="names"
value="seq,errCode,errMsg" />
</bean>
</property>
</bean>
</property>
</bean>
<bean id="dummyWriter" class="src.test.DummyItemWriter" scope="step"/>
The problem is when we use FlatFileItemWriter,we must use batch:streams to create the outfile.But if we use batch:streams,the outFile will create when the job start.
IF we do not use batch:streams,it will throw this errlog
org.springframework.batch.item.WriterNotOpenException: Writer must be open before it can be written to
Does itemWriter can not create file by himself?
You can use the shouldDeleteIfEmpty parameter of the FlatFileItemWriter
which is designed for this use case.