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
?
Asked
Active
Viewed 4,635 times
9

informatik01
- 16,038
- 10
- 74
- 104

fonet
- 91
- 1
- 2
-
Limitations: http://stackoverflow.com/questions/8476419/java-watchservice-not-generating-events-while-watching-mapped-drives – Joop Eggen May 17 '13 at 16:08
2 Answers
2
Generally you provide the directory name of the file when starting the watchservice. Here is a tutorial demonstrating how that works:
http://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes
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);

Bill the Lizard
- 398,270
- 210
- 566
- 880

patrickmdnet
- 3,332
- 1
- 29
- 34
-
1Note 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](http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java) example. – Nick Klauer Dec 31 '12 at 21:19
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

nurgasemetey
- 752
- 3
- 15
- 39