I am using Java 7, java.nio.file.WatchEvent
along with the WatchService
. After registering, when I poll for ENTRY_MODIFY events, I cannot get to the absolute path of the file for the event. Is there any way to get to the absolute path of the file from WatchEvent object?

- 11,875
- 18
- 85
- 108

- 567
- 2
- 8
- 16
4 Answers
You need to get the parent directory from the WatchKey to resolve the full path
WatchKey key;
WatchEvent<Path> event;
Path dir = (Path)key.watchable();
Path fullPath = dir.resolve(event.context());
This piece of code reads like it needs accompanying documentation to be grasped, it makes little sense on its own. What were their intentions with this particular API design?
And this is only the beginning of possibly unintuitive usage. Java's file watcher API is subjectively inferior to alternative libraries.

- 7,720
- 2
- 35
- 65

- 44,725
- 9
- 65
- 93
-
7you should down-vote then. but people eventually will find it out on their own. you need hundreds of lines of extra code to reach what you wanted in the beginning: to know what files are changed. and still there's no way to achieve this with absolute correctness. there is something seriously seriously wrong with the nio team. – irreputable Oct 18 '11 at 03:35
-
5You misunderstand. Your answer is good and deserves an upvote, and I have no great opinion about the merits of java.nio.file, but the last two words of your answer don't do it justice. Facts weigh more than abuse. – user207421 Oct 18 '11 at 04:44
-
1How do you deal with multiple watched directories? I’m watching a directory and all its subdirectories, and can’t know in which subdirectory is the modified/created file. – bfontaine Jun 20 '14 at 09:28
-
2Apache Commons IO has a much simpler directory watcher. Like irreputable, I'm scratching my head over Java's implementation. – Todd Mar 06 '17 at 03:52
Granted that you'll want to watch multiple directories (e.g. monitoring a file tree for change) storing the registered WatchKey
and it's associated Path
in a Map<WatchKey, Path>
would also be a viable solution.
When an event is triggered the Map
could be asked for the associated Path
with the given WatchKey
and then the Path
of the changed file could be resolved with the help of the Path
the WatchKey
is associated with.
Dependig on what object you got have, you can get absolute path of it:
Path.toAbsolutePath()
File.getAbsoluteFile()

- 14
- 2