Javawatchservice,如何找到创建文件的目录?

Java watchservice, how to find the directory where the file was created?

我正在尝试使用 Java Watchservice (NIO) 来监视多个目录,我可以在所有目录中看到创建事件,但我无法追溯到创建文件的目录。

例如,每当创建一个新文件时,我只能看到一个文件名(没有路径),如何知道创建事件是否在 faxfolder 或 faxfolder2 上触发

System.out.println("START MONITORING  **************");


Path faxFolder = Paths.get("E:\activiti\monitor\m1");
Path faxFolder2 = Paths.get("E:\activiti\monitor\m2");
WatchService watchService = FileSystems.getDefault().newWatchService();
faxFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
faxFolder2.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);


boolean valid = true;
WatchKey watchKey = watchService.take();
for (WatchEvent<?> event : watchKey.pollEvents()) {
    WatchEvent.Kind kind = event.kind();
    if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
        String fileName = event.context().toString();
        System.out.println(fileName);

    }
}
Path newFile = ev.context();
Path absolutePath = newFile.toAbsolutePath();

当您注册 watchService 时,您会得到该目录的 WatchKey。你应该记住哪个键对应哪个目录。

System.out.println("START MONITORING  **************");


Path faxFolder = Paths.get("E:\activiti\monitor\m1");
Path faxFolder2 = Paths.get("E:\activiti\monitor\m2");
WatchService watchService = FileSystems.getDefault().newWatchService();
Map<WatchKey,Path> keyMap = new HashMap<>();
WatchKey watchKey1 = faxFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
keyMap.put(watchKey1, faxFolder);
WatchKey watchKey2 = faxFolder2.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
keyMap.put(watchKey2, faxFolder2);


while (!Thread.currentThread().isInterrupted()) {
    WatchKey watchKey = watchService.take();
    Path dir = keyMap.get(watchKey);
    for (WatchEvent<?> event : watchKey.pollEvents()) {
        WatchEvent.Kind kind = event.kind();
        if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
            Path relativePath = (Path) event.context();
            String fileName = dir.resolve(relativePath).toString();
            System.out.println(fileName);

        }
    }
}

您的监控循环应该等待事件 (WatchService.take()),然后解决事件 (watchKey.pollEvents())。所有这些都将适用于同一个 WatchKey。然后取next key,可能是针对另一个目录的。