我正在学习Java和Spring Boot,我需要做一个应用程序来处理txt文件。所以我有一个文件夹,在这个文件夹中,我接收txt文件。该应用程序将等待一个文件夹中的txt文件,并将已处理的txt文件放入另一个文件夹。在特定文件夹中收到txt文件后,应用将对其进行处理,然后等待另一个txt文件进行处理。我知道如何进行业务逻辑处理以及如何在处理后导出txt文件,但是该如何等待呢?任何反馈将不胜感激!谢谢!
由于您使用的是Spring Boot,因此我将使用其计划服务来检查计划中的新文件。您必须将@EnableScheduling
标签添加到您的配置中。然后定义一个按计划运行的方法。
@Scheduled(fixedDelay = 60000)
public void checkForNewProductFiles() {
检查Spring集成,它正是您要实现的目标。
下面是示例代码,该示例代码侦听远程位置的任何新文件并进行处理(如果有)。>
@Bean
public IntegrationFlow sftpInboundFlow() throws IOException {
if (update.isClearLocalDir) {
FileUtils.clearLocalDir(update.localPath);
}
return IntegrationFlows
.from(
Sftp.inboundAdapter(sftpSessionFactory)
.preserveTimestamp(true)
.deleteRemoteFiles(true)
.regexFilter(update.filterExpr)
.localDirectory(new File(update.localPath))
.autoCreateLocalDirectory(true)
.remoteDirectory(update.remotePath),
e -> e.id("sftpInboundAdapter")
.autoStartup(true)
.poller(Pollers.fixedRate(update.pollingFrequency)
.maxMessagesPerPoll(1)))
.channel(updateFileChannel())
.get();
}
@Bean
public DirectChannel updateFileChannel() {
return new DirectChannel();
}
@Bean
public IntegrationFlow orderUpdateFlow() {
return IntegrationFlows.from(updateFileChannel())
.handle(fileProcessor, "handleUpdate")
.get();
}