How can I watch subdirectory for changes with WatchService? (Java)
Asked Answered
D

2

9

I want to watch some directory for changes and her subdirectories. I tried to do this with WatchService but I can't know from which directory the file was changed. How can I retrieve the full path from the WatchEvent?

Deification answered 9/4, 2011 at 22:4 Comment(1)
Limitations: #8476919Tribromoethanol
M
2

Generally you provide the directory name of the file when starting the watchservice. Here is a tutorial demonstrating how that works:

https://docs.oracle.com/javase/tutorial/essential/io/notification.html https://docs.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java

From the tutorial:

   Path dir = ...;
   try {
       WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
   }[.....]

when you catch a notification:

   //The filename is the context of the event.
   WatchEvent<Path> ev = (WatchEvent<Path>)event;
   Path filename = ev.context();

   Path child = dir.resolve(filename);
Michell answered 9/4, 2011 at 22:43 Comment(1)
Note that WatchService won't automatically track subdirectories and subdirectory creation by default, so you would have to both walk the directory path and register each directory at the start, as well as catch the type of file change, and register that as well (if it's a directory). You can see how they have examples of it in the WatchDir example.Aspergillosis
C
1

For users who use Spring:

With Spring 4.2 WatchServiceDirectoryScanner is introduced. Now it can also catch sub directory changes.

For more information, Javadocs on WatchServiceDirectoryScanner

Calista answered 15/9, 2015 at 18:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.