如果我开始监视文件夹 A
中的更改,删除并重新创建它,那么 WatchService 将不会触发该文件夹的任何事件。我想在 WatchService 忘记文件夹 A
后重新观看它。
如何检查文件夹 A
是否仍被 WatchService 跟踪?
最佳答案
无需监视父文件夹,有一种方法可以知道您的监视程序是否不再工作,以便您可以重新创建它。
下面的代码应该可以帮到你。
WatchService watchService = null;
String folderString = "Your path here";
do
{
Thread.sleep(1000);
File dir = new File(folderString);
if (!dir.exists())
continue;
watchService = FileSystems.getDefault().newWatchService();
Path folder = Paths.get(folderString);
folder.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
boolean watchStillOperational = false;
do
{
WatchKey watchKey = watchService.take();
for (WatchEvent<?> event : watchKey.pollEvents())
{
.....
}
// The following line indicates if the watch no longer works
// If the folder was deleted this will return false.
watchStillOperational = watchKey.reset();
} while (watchStillOperational)
} while(true)
关于java - 如何检查 WatchService 跟踪的文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17981549/