4

I'm trying out WatchService with Java 7, to monitor a folder. I want it to monitor any files or folders being added to the path registered with the WatchService.

If I add a folder to the registered path it detects it correctly as ENTRY_CREATE and returns the name of the folder in watchEvent.context(). But if I add a folder to that folder than again it is detected but watchEvent.context() returns the same folder and ENTRY_MODIFY, because that folder has been modified by adding another folder.

So I understand this but don't know if I should be registering every folder within the structure and or just registering the top folder and listening or CREATE and MODIFY

Paul Taylor
  • 13,411
  • 42
  • 184
  • 351
  • http://docs.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java should be useful, it shows how to add WatchKeys recursively by walking the FileTree – Franz Ebner Dec 11 '13 at 10:29

1 Answers1

4

There is no direct support for that across platforms. For Windows there is an ExtendedWatchEventModifier.FILE_TREE that will watch a directory recursively. However there is no equivalent functionality on Mac or Linux. Also, note that ExtendedWatchEventModifier is an extension and not part of the standard definition.

You have to listen for CREATE and DELETE. When the object created (deleted) is a directory you need to add (remove) a new watch on the subdirectory.

Devon_C_Miller
  • 16,248
  • 3
  • 45
  • 71
  • Thanks, you mean this http://jpathwatch.sourceforge.net/ . Looks like it may support OSX now buts seems a safer bet for me to just register every folder – Paul Taylor Oct 15 '12 at 12:08
  • I believe that is where much of the WatchService concepts originated. but it is part of OpenJDK7 as well: http://www.docjar.com/html/api/com/sun/nio/file/ExtendedWatchEventModifier.java.html Note that this is a com.sun.* class. – Devon_C_Miller Oct 15 '12 at 12:17
  • 1
    I found ExtendedWatchEventModifier in the jdk.unsupported library at least since Java 10. – marc Mar 05 '19 at 17:19