如果我开始监视文件夹中的更改A
,删除并重新创建它,那么 WatchService 将不会触发该文件夹的任何事件。我想在 WatchServiceA
忘记文件夹后重新观看它。
如何检查该文件夹A
是否仍被 WatchService 跟踪?
如果我开始监视文件夹中的更改A
,删除并重新创建它,那么 WatchService 将不会触发该文件夹的任何事件。我想在 WatchServiceA
忘记文件夹后重新观看它。
如何检查该文件夹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)
您的问题是您删除了监视文件夹,然后创建了一个具有相同名称的新文件夹,从WatchService
角度来看,这是一个不同的文件夹。被监视的文件夹可能仍在垃圾箱/回收站中被监视。
如果您希望能够从中恢复,最简单的方法是观看超级目录。您可能还幸运地定期检查文件夹的路径,如果它被删除,它将改变。
我觉得这个问题是糟糕计划的症状。你能不能很好地保护不容易删除的文件夹(或超级文件夹)。