7

我一直在玩 the java.nio.file.WatchService,并注意到从Paths 返回的 sWatchEvent.context()不正确返回.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系统属性解析的,而不是Path用于WatchService注册的。这是一个问题,因为当我尝试使用(例如Files.copy())从我收到的返回的路径时,WatchEvent我收到了一个java.nio.file.NoSuchFileException,这是预期的,因为在这个路径上没有这样的文件。我是否遗漏了什么或者这是 JRE 中的错误?

4

1 回答 1

13

这不是错误,但肯定令人困惑。

如果WatchEvent.context()返回 aPath那么它是相对的:

在 ENTRY_CREATE、ENTRY_DELETE 和 ENTRY_MODIFY 事件的情况下,上下文是一个 Path,它是向监视服务注册的目录与创建、删除或修改的条目之间的相对路径。

现在,如果您通过调用将此类路径转换为绝对路径,toAbsolutePath()则不会相对于监视目录而是相对于默认目录。

此方法以与实现相关的方式解析路径,通常通过根据文件系统默认目录解析路径。根据实现,如果文件系统不可访问,此方法可能会引发 I/O 错误。

因此,要将路径转换为您需要使用的绝对路径

watchedDirectory.resolve(createdFile);
于 2015-09-21T09:38:22.583 回答