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

二次信任 提交于 2019-12-03 06:36:23

问题


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?


回答1:


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.




回答2:


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.




回答3:


Dependig on what object you got have, you can get absolute path of it:

Path.toAbsolutePath()

File.getAbsoluteFile()




回答4:


String fullPath = path.toString() + "\\"+ event.context().toString();

:D



来源:https://stackoverflow.com/questions/7801662/java-nio-file-watchevent-gives-me-only-relative-path-how-can-i-get-the-absolute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!