My code is as follows:
try {
watcher = FileSystems.getDefault().newWatchService();
registerAll(path);
} catch (IOException e) {
return;
}
while (true){
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
continue;
}
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path filename = ev.context();
Path dir = (Path)key.watchable();
Path child = dir.resolve(filename);
File file = child.toFile();
System.out.println(kind + " | " + file);
if(kind == ENTRY_CREATE && file.isDirectory()){
register(file);//transforma file em path e registra
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
The problem is that when a subfolder is deleted, it counts as overflow (when I use debug the kind is overflow at the time) and the key.reset ends up being invalid, and the loop ends.