I see a strange behaviour ( not sure i this is expected behaviour ) using java.nio.file.WatchService.
The problem is I have a folder registered with WatchService. When I copy a new file into this folder, then two WatchEvent get generated, one each for :
'ENTRY_CREATE' and 'ENTRY_MODIFY'.
As far as I understand, a new file ( copied from other directory which is not getting watched) must create only one event, i.e : 'ENTRY_CREATE'.
Can anybody explain why the extra event 'ENTRY_MODIFY' gets created ?
My code:
public void watch() {
WatchKey key = watcher.poll();
//log.info("Watcher scheduler running. Watch key {}", key.hashCode());
if (key != null) {
Workflow workflow = keys.get(key);
log.info("Runing watcher for key '{}' and workflow {}", key.hashCode(), workflow.getName());
File hotFolder = new File(workflow.getFolderPath());
Path dir = hotFolder.toPath();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
log.info("Polling event for name {} and child {} and dir {}", name.toFile(), child.toFile(), dir.toFile());
if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS))
continue;
try {
switch (event.kind().name()) {
case "ENTRY_CREATE":
log.info("New file {}", child.toFile());
fileService.processNewFile(child.toFile(), workflow);
break;
case "ENTRY_MODIFY":
log.info("File modified.... {}", child.toFile());
fileService.processModifiedFile(child.toFile(),
workflow);
break;
default:
log.error("Unknown event {} for file {}", event.kind()
.name(), child.toFile());
break;
}
// Operation op = Operation.from(event.kind());
// if (op != null)
// publisher.publishEvent(new FileEvent(child.toFile(),
// workflow, op));
} catch (Throwable t) {
log.warn("Error while procesing file event", t);
}
}
key.reset();
}
}
So when I copy a file, say name = "abc.txt", the logs display:
New file abc.txt
File modified.... abc.txt
Any inputs is highly solicited.