Je test Java 7 en ce moment et je suis tombé sur un comportement inattendu en suivant le tutoriel
sur le blog de Oracle.(http://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes)
J'ai fait les étapes suivantes :
mkdir ~/tmp
touch ~/tmp/toto
Puis j'ai regardé les évènements produits dans ~/tmp/toto et cela fonctionne bien (Si je crée un fichier, j'ai bien l' évènement CREATED).
Puis j'ai fait cela :
mv ~/tmp ~/tmp.old
touch ~/tmp.old/titi
J'ai regardé si il y avait des évènements et il y en avait ! Hors c'est le répertoire que je venais de mover donc je m'attendais plutôt à une exception envoyée par la méthode reset() !
J'ai pris mon courage à deux mains et j'ai posté un message sur le site d'Oracle ...
Voici l'exemple du blog d'Oracle:
for (;;) {
//wait for key to be signaled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
for (WatchEvent event: key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
//This key is registered only for ENTRY_CREATE events,
//but an OVERFLOW event can occur regardless if events are
//lost or discarded.
if (kind == OVERFLOW) {
continue;
}
//The filename is the context of the event.
WatchEvent ev = (WatchEvent)event;
Path filename = ev.context();
//Verify that the new file is a text file.
try {
//Resolve the filename against the directory.
//If the filename is "test" and the directory is "foo",
//the resolved name is "test/foo".
Path child = dir.resolve(filename);
if (!Files.probeContentType(child).equals("text/plain")) {
System.err.format("New file '%s' is not a plain text file.%n", filename);
continue;
}
} catch (IOException x) {
System.err.println(x);
continue;
}
//Email the file to the specified email alias.
System.out.format("Emailing file %s%n", filename);
//Details left to reader....
}
//Reset the key -- this step is critical if you want to receive
//further watch events. If the key is no longer valid, the directory
//is inaccessible so exit the loop.
boolean valid = key.reset();
if (!valid) {
break;
}
}