Spring 入站通道适配器 - 如何自动删除超过 10 天的文件夹和文件



Integration.xml- 这将获取目录中的所有文件

<int-file:inbound-channel-adapter id="delFiles" channel="delFiles" 
directory="C:/abc/abc" use-watch-service="true" prevent-duplicates="false" auto-startup="true"
watch-events="CREATE,MODIFY">
<int:poller fixed-delay="1000"/>
<int-file:nio-locker/>
</int-file:inbound-channel-adapter>

我需要删除该文件夹和子文件夹中超过 10 天的所有文件。有人可以帮忙吗?

听者

@Transformer(inputChannel="delFiles")
public JobLaunchRequest deleteJob(Message<File> message) throws IOException {
Long timeStamp = message.getHeaders().getTimestamp();
return JobHandler.deleteJob(message.getPayload(), jobRepository, fileProcessor, timeStamp);
}

处理器

public static JobLaunchRequest deleteJob(File file, JobRepository jobRepository, Job fileProcessor, Long timeStamp) throws IOException {
//Is there a way in spring integration whether I can check this easily?
//How to check for folder and subfolders?
// This will check for files once it's dropped.
// How to run this job daily to check the file's age and delete?
}

这不是<int-file:inbound-channel-adapter>的责任。这实际上是关于根据您提供的过滤设置从目录中轮询文件。

如果您对旧文件不感兴趣,则可以实现自定义FileListFilter来跳过非常旧的文件。

如果您仍然想删除这些旧文件作为某些应用程序功能,则需要查看其他解决方案,例如@Scheduled迭代该目录中的文件并删除它们的方法,例如每天一次,比如说在午夜。

您也可以只删除逻辑中的 和 中已处理的文件。由于您使用prevent-duplicates="false",您将一次又一次地轮询同一个文件。

要执行目录清理,您不需要 Spring 集成:

public void recursiveDelete(File file) {
if (file != null && file.exists()) {
File[] files = file.listFiles();
if (files != null) {
for (File fyle : files) {
if (fyle.isDirectory()) {
recursiveDelete(fyle);
}
else {
if (fyle.lastModified() > 10 * 24 * 60 * 60 * 1000) {
fyle.delete();
}
}
}
}
}
}

(你可以稍微改进一下这个功能:还没有测试过...