In spring batch , I am using MultiResourceItemReader to read multiple files from the directory. Then I am using a FlatFileItemReader as a delegate to process individual files. My usecase is to delete the file once it is processed completely(READ-WRITE is done) and then multiResourceitemReader has to pick another file and it has to go on.
I tried FileDeletingTasklet to delete file in a directory, but as per Spring docs , the execute method will be called only once. How can I achieve delete on file which are processed(READ-WRITE), but I don't want to go with entire directory delete once all files are processed completely in the directory.
Below is the job I am using :
<batch:job id="getEmpDetails">
<batch:step id="readAndProcess" next="deleteProcessedFile">
<batch:tasklet>
<batch:chunk reader="readEmpDetails" writer="writeEmpDetails" commit-interval="100">
</batch:chunk>
</batch:tasklet>
</batch:step>
<batch:step id="deleteProcessedFile">
<batch:tasklet ref="fileDeletingTasklet" />
</batch:step>
</batch:job>
<bean id="fileDeletingTasklet" class="com.test.FileDeletingTasklet">
<property name="directoryResource">
<bean id="directory" class="org.springframework.core.io.FileSystemResource">
<constructor-arg value="E:/testDir/file1.txt" />
</bean>
</property>
</bean>
Override the FlatFileItemReader.setResource()
method as
public void setResource(Resource resource) {
this.resource = resource;
this.delegateReader.setResource(resource);
}
and manage file deletion in FlatFileItemReader.read()
when stream is totally consumed
public T read() throws Exception {
T o = this.delegateReader.read();
if (o == null) {
// Perform deletion here
deleteFile(this.resource);
}
return o;
}
I have achieved it by adding proceeded file name in jobcontext as list and then in my next step I execute my custom tasklet to delete file or move files based on the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With