Forum Stats

  • 3,838,030 Users
  • 2,262,321 Discussions


WatchService WatchKey.cancel() is really forever ?

2766010 Member Posts: 2
edited Nov 26, 2014 7:47AM in Java Desktop Applications

I am using java 8 on linux ubuntu 12.04 following the guidelines Watching a Directory for Changes (The Java™ Tutorials > Essential Classes > Basic I/O)

This works but I notice that once I cancel a watchkey with watchkey.cancel() , I seem to be unable to reenable it again. So I can never watch a directory after I have cancelled the corresponding watchkey (even after reboot ) ?

The API Doc says that " Once cancelled, a watch key remains forever invalid."

What does "forever" mean ? There must be a way to re-watch a dir after the key has been cancelled.

Thanks for your help.


  • 2766010
    2766010 Member Posts: 2

    In reply to my request: sorry , I had a logical error in my test case that did not clean up the to-be-watched directory structure correctly.

    Remains the question: what is "forever" ? Until a new watchservice is created ?

    Sorry for the noise.

  • 2803364
    2803364 Member Posts: 10
    edited Nov 26, 2014 7:47AM

    Registering recursively will work as Sotirios has indicated. This effectively registers each directory/sub-directory that currently exists.

    You can alternatively import and use *com.sun.nio.file.ExtendedWatchEventModifier.FILE_TREE* as in:

    <span class="pln" style="background: transparent;">dir</span><span class="pun" style="background: transparent;">.</span><span class="kwd" style="color: #00008b; background: transparent;">register</span><span class="pun" style="background: transparent;">(</span><span class="pln" style="background: transparent;">watcher</span><span class="pun" style="background: transparent;">,</span><span class="pln" style="background: transparent;"> standardEventsArray</span><span class="pun" style="background: transparent;">,</span><span class="pln" style="background: transparent;"> </span><span class="typ" style="color: #2b91af; background: transparent;">ExtendedWatchEventModifier</span><span class="pun" style="background: transparent;">.</span><span class="pln" style="background: transparent;">FILE_TREE</span><span class="pun" style="background: transparent;">);</span>

    This will watch the entire sub-tree for change AND account for added directories and sub-directories.

    Otherwise you will have to monitor for any new directories/sub-directories and register them also. There can also be an issue with deleting parts of the directory hierarchy since each registered directory has a handle watching it so the (lowest) sub-directories need to be removed first when deleting parts of the structure.

This discussion has been closed.