java.nio.file.WatchEvent gives me only relative path. How can I get the absolute path of the modified file?

user1000258 picture user1000258 · Oct 18, 2011 · Viewed 10.4k times · Source

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?

Answer

irreputable picture irreputable · Oct 18, 2011

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.