简体   繁体   中英

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

I am trying to use Java Watchservice (NIO) to watch mutiple directories , I can see the create event in all directories but I cant trace back to directory where the file was created.

For eg , whenever a new file is created I can only see a filename (without path) , how to know whether the create event triggered on faxfolder or 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);

    }
}

When you register the watchService, you are given a WatchKey for that directory. You should remember which key goes with which directory.

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);

        }
    }
}

Your monitoring loop should wait for events ( WatchService.take() ) and then resolve the events ( watchKey.pollEvents() ). All of which will be applicable to the same WatchKey . Then take the next key, which may be for another directory.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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