我可以使用 WatchService(不是整个目录)监视单个文件的更改吗? [英] Can I watch for single file change with WatchService (not the whole directory)?
本文介绍了我可以使用 WatchService(不是整个目录)监视单个文件的更改吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试注册文件而不是目录时,抛出 java.nio.file.NotDirectoryException
.我可以监听单个文件的变化,而不是整个目录吗?
When I'm trying to register a file instead of a directory java.nio.file.NotDirectoryException
is thrown. Can I listen for a single file change, not the whole directory?
推荐答案
只需过滤目录中所需文件的事件:
Just filter the events for the file you want in the directory:
final Path path = FileSystems.getDefault().getPath(System.getProperty("user.home"), "Desktop");
System.out.println(path);
try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
final WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
final WatchKey wk = watchService.take();
for (WatchEvent<?> event : wk.pollEvents()) {
//we only register "ENTRY_MODIFY" so the context is always a Path.
final Path changed = (Path) event.context();
System.out.println(changed);
if (changed.endsWith("myFile.txt")) {
System.out.println("My file has changed");
}
}
// reset the key
boolean valid = wk.reset();
if (!valid) {
System.out.println("Key has been unregisterede");
}
}
}
这里我们检查修改后的文件是否是myFile.txt",如果是则做任何事情.
Here we check whether the changed file is "myFile.txt", if it is then do whatever.
这篇关于我可以使用 WatchService(不是整个目录)监视单个文件的更改吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文