我一直在尝试使用java.nio.file.WatchService
并注意到从WatchEvent.context()
返回的Path
不会返回正确的.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 中的一个错误?
((Path) key.watchable()).resolve( ((WatchEvent<Path>) event).context() )
。 - Guus