java.nio.file.WatchEvent仅提供相对路径.如何获取修改后的文件的绝对路径? [英] java.nio.file.WatchEvent gives me only relative path. How can I get the absolute path of the modified file?
问题描述
我正在使用Java 7,java.nio.file.WatchEvent
和WatchService
.注册后,当我轮询ENTRY_MODIFY事件时,无法到达该事件的文件的绝对路径.有什么方法可以从WatchEvent对象获取文件的绝对路径?
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?
推荐答案
您需要从WatchKey中获取父目录以解析完整路径
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());
这段代码看起来像需要随附的文档一样阅读,仅凭其本身就没有多大意义.他们对这种特定的API设计有何意图?
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?
这仅仅是可能不直观的用法的开始. Java的文件监视程序API在主观上不如其他库.
And this is only the beginning of possibly unintuitive usage. Java's file watcher API is subjectively inferior to alternative libraries.
这篇关于java.nio.file.WatchEvent仅提供相对路径.如何获取修改后的文件的绝对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!