Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

java - Spring batch-Delete the flatfile from directory after processed

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...