سؤال

If I start watching for changes in folder A, delete and recreate it then WatchService will not trigger any events for this folder. I wanna rewatch folder A after it was forgotten by WatchService.

How can I check that folder A is still tracked by WatchService?

هل كانت مفيدة؟

المحلول

There is no need to monitor the parent folder, there is a way to know if the watcher you have no longer works so you can recreate it.

The following code should help you out.

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)

نصائح أخرى

Your problem is you deleted the watched folder, then made a new folder with the same name, which from WatchService point of view is a different folder. The watched folder is likely still being watched in the trash/recycle bin.

If you want to be able to recover from this, the easiest way is to watch the super-directory. You might also have luck periodically checking the path to the folder, which will change if its deleted.

I feel like this problem is a symptom of bad planning. Can you not just protect the folder well enough (or a super-folder) that its not easy to delete.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top