gpt4 book ai didi

spring - 无法在 Spring Batch 中的 afterStep 中清理文件夹

转载 作者:行者123 更新时间:2023-12-04 20:43:20 25 4
gpt4 key购买 nike

我有一份工作,我处理并将所有文件从一个目录复制到另一个目录。 步骤后我想删除第一个目录,但在尝试删除处理的最后一个文件(复制)时出现错误。结果是一个只有 的文件夹。一 无法删除的文件,该文件恰好是最后处理的文件
我的 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>

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

关于spring - 无法在 Spring Batch 中的 afterStep 中清理文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22326158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com