我正在编写一段代码,我需要使用 Apache Camel 处理位于服务器上的文件。我需要实现以下步骤:
1 --> 控件应该迭代位于特定文件夹中的所有文件。
2 --> 然后它应该检查哪个文件早于 15 天。
3 --> 然后删除超过 15 天的文件。
现在,我可以实现第一步和第二步了。但我无法删除该文件。 我创建了一条像这样的 Camel 路线:
<camel:route id="lastModifiedFMFileCheckRoute">
<camel:from uri="sftp://someUser@someServer/usableFiles?password=secret"/>
<camel:setProperty propertyName="availableFile">
<camel:simple>${body}</camel:simple>
</camel:setProperty>
<camel:process ref="fileModificationDateProcessor" />
</camel:route>
我的处理器的处理方法如下所示,我在其中检查文件是否超过 15 天。
@Override
public void process(Exchange exchange) throws Exception {
boolean isFileDeleted = false;
@SuppressWarnings("rawtypes")
GenericFile currentFile = (GenericFile)exchange.getProperty("availableFile", RemoteFile.class);
Date currentDate = new Date();
int numberOfDays = (int)( (currentDate.getTime() - availableFile.getLastModified()) / MILLISECONDS_TO_DAY_CONVERTER_VALUE);
if(numberOfDays > 15){
String absoluteFilePath = availableFile.getAbsoluteFilePath();
//TODO The file (currentFile) needs to be deleted. As it is older than 15 days.
}
exchange.getOut().setBody(fileDeleted);
}
这里如何实现所需文件的删除。
最佳答案
在您的(s)ftp端点上,您可以设置delete=true
和filter=#ageFilter
,其中ageFilter是对自定义文件过滤器的引用,仅接受较旧的文件超过 15 天。
public class AgeFilter<T> implements GenericFileFilter<T> {
@Override
public boolean accept(final GenericFile<T> file) {
long now = System.currentTimeMillis();
long lastModified = file.getLastModified();
return now-lastModified > CUT_OFF_AGE;
}
}
在路由结束时,FTP 端点将删除此过滤器选择的所有文件。
作为文件过滤器的替代方案,如果文件不超过 15 天,您可以在处理器中抛出 RuntimeException
。这将使您的路由失败,并将文件保留在远程服务器上。然而,使用异常来控制流确实不是一个好的做法。
关于java - 无法使用 apache Camel FTP 删除位于服务器上的远程文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21432776/