繁体   English   中英

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

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

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

例如,每当创建一个新文件时,我只能看到一个文件名(没有路径),如何知道创建事件是在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 您应该记住哪个键与哪个目录一起使用。

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 然后,取下一个密钥,该密钥可能用于另一个目录。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM