gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:23:18 29 4
gpt4 key购买 nike

我正在尝试使用 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);

}
}

最佳答案

当您注册 watchService 时,您将获得该目录的 WatchKey。您应该记住哪个 key 对应哪个目录。

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。然后取下一个 key ,这可能是另一个目录。

关于Java watchservice,如何找到创建文件的目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55563184/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com