WatchService WatchKey.cancel() is really forever ? — oracle-tech

    Forum Stats

  • 3,702,038 Users
  • 2,239,552 Discussions
  • 7,835,729 Comments

Discussions

WatchService WatchKey.cancel() is really forever ?

27660102766010 Posts: 2
edited November 2014 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.

Answers

  • 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.

  • 28033642803364 Posts: 10
    edited November 2014

    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.