gpt4 book ai didi

java - 如何在 Spring 监控文件夹/目录?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:24:48 26 4
gpt4 key购买 nike

我不想在 Spring 编写 Spring Boot 应用程序,它将监视 Windows 中的目录,当我更改子文件夹或添加新文件夹或删除现有文件夹时,我想获取相关信息。

我该怎么做?我读过这个: http://docs.spring.io/spring-integration/reference/html/files.html以及谷歌“spring file watcher”下的每个结果,但我找不到解决方案...

你有这样的好文章或例子吗?我不希望它像这样:

@SpringBootApplication
@EnableIntegration
public class SpringApp{

public static void main(String[] args) {
SpringApplication.run(SpringApp.class, args);
}

@Bean
public WatchService watcherService() {
...//define WatchService here
}
}

问候

最佳答案

spring-boot-devtoolsFileSystemWatcher

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

FileWatcherConfig

@Configuration
public class FileWatcherConfig {
@Bean
public FileSystemWatcher fileSystemWatcher() {
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(true, Duration.ofMillis(5000L), Duration.ofMillis(3000L));
fileSystemWatcher.addSourceFolder(new File("/path/to/folder"));
fileSystemWatcher.addListener(new MyFileChangeListener());
fileSystemWatcher.start();
System.out.println("started fileSystemWatcher");
return fileSystemWatcher;
}

@PreDestroy
public void onDestroy() throws Exception {
fileSystemWatcher().stop();
}
}

MyFileChangeListener

@Component
public class MyFileChangeListener implements FileChangeListener {

@Override
public void onChange(Set<ChangedFiles> changeSet) {
for(ChangedFiles cfiles : changeSet) {
for(ChangedFile cfile: cfiles.getFiles()) {
if( /* (cfile.getType().equals(Type.MODIFY)
|| cfile.getType().equals(Type.ADD)
|| cfile.getType().equals(Type.DELETE) ) && */ !isLocked(cfile.getFile().toPath())) {
System.out.println("Operation: " + cfile.getType()
+ " On file: "+ cfile.getFile().getName() + " is done");
}
}
}
}

private boolean isLocked(Path path) {
try (FileChannel ch = FileChannel.open(path, StandardOpenOption.WRITE); FileLock lock = ch.tryLock()) {
return lock == null;
} catch (IOException e) {
return true;
}
}

}

关于java - 如何在 Spring 监控文件夹/目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40020999/

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