我想观察一些目录的变化和她的子目录。我试图这样做,WatchService
但我不知道文件是从哪个目录更改的。如何从 中检索完整路径WatchEvent
?
问问题
4391 次
2 回答
2
通常,您在启动 watchservice 时提供文件的目录名。这是一个演示如何工作的教程:
http://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes
从教程:
Path dir = ...;
try {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
}[.....]
当您收到通知时:
//The filename is the context of the event.
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path filename = ev.context();
Path child = dir.resolve(filename);
于 2011-04-09T22:43:33.623 回答
1
对于使用 Spring 的用户:
随着 Spring 4.2 WatchServiceDirectoryScanner的引入。现在它还可以捕捉子目录的变化。
于 2015-09-15T18:28:37.870 回答