Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 280
user1000258 Avatar asked Oct 18 '11 02:10

user1000258


People also ask

How do I find the absolute path of a path?

The function getAbsolutePath() will return the absolute (complete) path from the root directories. If the file object is created with an absolute path then getPath() and getAbsolutePath() will give the same results.

How do you declare an absolute path in Java?

A path is either relative or absolute. An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path. All of the information needed to locate the file is contained in the path string.

What is absolute and relative path in Java?

A path can be absolute or relative. An absolute path contains the full path from the root of the file system down to the file or directory it points to. A relative path contains the path to the file or directory relative to some other path.


2 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.

like image 132
irreputable Avatar answered Oct 17 '22 15:10

irreputable


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.

like image 35
rmoestl Avatar answered Oct 17 '22 15:10

rmoestl