【发布时间】:2015-09-21 09:10:32
【问题描述】:
我一直在玩java.nio.file.WatchService 并注意到从WatchEvent.context() 返回的Paths 没有返回正确的.toAbsolutePath()。这是一个示例应用程序:
public class FsWatcher {
public static void main(String[] args) throws IOException, InterruptedException {
if (args.length != 1) {
System.err.println("Invalid number of arguments: " + args.length);
return;
}
//Run the application with absolute path like /home/<username>
final Path watchedDirectory = Paths.get(args[0]).toAbsolutePath();
final FileSystem fileSystem = FileSystems.getDefault();
final WatchService watchService = fileSystem.newWatchService();
watchedDirectory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
while (true) {
WatchKey watchKey = watchService.take();
for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
if (watchEvent.kind().equals(StandardWatchEventKinds.OVERFLOW)) {
continue;
}
final Path createdFile = (Path) watchEvent.context();
final Path expectedAbsolutePath = watchedDirectory.resolve(createdFile);
System.out.println("Context path: " + createdFile);
System.out.println("Context absolute path: " + createdFile.toAbsolutePath());
System.out.println("Expected absolute path: " + expectedAbsolutePath);
System.out.println("usr.dir: " + System.getProperty("user.dir"));
}
watchKey.reset();
}
}
}
示例输出:
Context path: document.txt
Context absolute path: /home/svetlin/workspaces/default/FsWatcher/document.txt
Expected absolute path: /home/svetlin/document.txt
usr.dir: /home/svetlin/workspaces/default/FsWatcher
似乎绝对路径是针对user.dir 系统属性解析的,而不是用于WatchService 注册的Path。这是一个问题,因为当我尝试使用(例如Files.copy())从WatchEvent 返回的路径时,我收到了java.nio.file.NoSuchFileException,这是预期的,因为此路径中没有这样的文件。我是否遗漏了什么或者这是 JRE 中的错误?
【问题讨论】:
标签: java nio watchservice java.nio.file