无法在Spring Batch中清除afterStep中的文件夹

我有一个工作,我处理和复制从目录到另一个目录的所有文件.在步骤后我想删除第一个目录,但我在尝试删除处理(复制)的最后一个文件时收到错误.结果是一个文件夹只有一个文件无法删除,此文件恰好是最后一次处理

我的StepExecutionListener看起来像这样:

public class CleanUpListener implements StepExecutionListener {

private static final Logger logger = LoggerFactory.getLogger(CleanUpListener.class);

private String folderToBeDeleted;

@Override
public ExitStatus afterStep(StepExecution arg0) {
    try {
        logger.info("Deleting folder: " + folderToBeDeleted + " ...");
        File file = new File(folderToBeDeleted);
        logger.info("folder contains: " + file.listFiles().length);
        FileUtils.deleteDirectory(file);
        logger.info("Deleted folder: " + folderToBeDeleted);
    } catch (IOException e) {
        logger.error("Failed to delete folder: " + folderToBeDeleted + " with exception: " + e.toString());
    }
    return null;
}

@Override
public void beforeStep(StepExecution arg0) {
    // TODO Auto-generated method stub

}

public String getFolderToBeDeleted() {
    return folderToBeDeleted;
}

public void setFolderToBeDeleted(String folderToBeDeleted) {
    this.folderToBeDeleted = folderToBeDeleted;
}

}

产生一个结果:

11/03/2014 13:53:56.804 [http-bio-8080-exec-2] [] INFO                 CleanUpListener - Line (29) Deleting folder: C:/Myfolder ...
11/03/2014 13:53:56.806 [http-bio-8080-exec-2] [] INFO                 CleanUpListener - Line (31) folder contains: 14
11/03/2014 13:53:56.826 [http-bio-8080-exec-2] [] ERROR                CleanUpListener - Line (35) Failed to delete folder: C:/Myfolder with exception: java.io.IOException: Unable to delete file: C:/Myfolder/14.xml

除最后一个处理的文件(14.xml)外,所有文件都被删除

更新:
读者的步骤:

<bean id="modelReader"
        class="org.springframework.batch.item.file.MultiResourceItemReader"
        scope="step">
        <property name="resources" value="file:${step3.reader.resource}/*.xml"></property>
        <property name="delegate" ref="staxPatentReader"></property>
        <property name="strict" value="true"></property>
    </bean>

    <bean id="staxPatentReader" class="org.springframework.batch.item.xml.StaxEventItemReader">
        <property name="fragmentRootElementName" value="Root" />
        <property name="unmarshaller" ref="modelMarshaller" />
    </bean>

    <bean id="modelMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
            <list>
                <value>com.sample.MyModel</value>
            </list>
        </property>
    </bean>

最佳答案 对于这种步骤,使用自定义
Tasklet实现.

class DeleteFilesTasklet implements Tasklet {
  execute(StepContribution, ChunkContext) throws Exception {
    // do deletion and return the right value
  }
}

在你的job.xml中

<job>// previous steps
  <step id="deleteFiles">
    <tasklet ref="deleteFiles" />
  </step>
  <bean class="DeleteFilesTasklet" id="deleteFiles" />
</job>

通过这种方式,您可以确保在上一步中已关闭所有文件(和其他资源).

点赞