Spring batch-Delete the flatfile from directory after processed

那年仲夏 提交于 2019-11-27 15:15:03

问题


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>

回答1:


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;
}



回答2:


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.



来源:https://stackoverflow.com/questions/23323535/spring-batch-delete-the-flatfile-from-directory-after-processed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!