1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| import java.io.IOException;
import java.nio.file.WatchEvent.Modifier;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Test {
private static FileSystem fs = FileSystems.getDefault();
private static WatchService ws = null;
@SuppressWarnings("restriction")
public static void main(String args[]) throws InterruptedException {
try {
try {
ws = fs.newWatchService();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
// Répertoire fictif pour des raisons de sécurités...
Path PathHome = fs.getPath("\\\\***.**.**.***\\tmp\\wajdi\\");
PathHome.register(ws, new WatchEvent.Kind<?>[]{
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY
}, com.sun.nio.file.ExtendedWatchEventModifier.FILE_TREE);
System.out.println("Ajout des répertoires terminés");
while(true){
WatchKey key = ws.take();
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
Path path = fs.getPath(key.watchable().toString(), event.context().toString());
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
if (!Files.isDirectory(path)){
System.out.println("Created : "+path.toFile().getAbsolutePath());
}
else {
path.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW, StandardWatchEventKinds.ENTRY_DELETE);
System.out.println(path.toFile().getAbsolutePath()+ " ajouté à la liste d'écoute");
}
}
}
boolean valid = key.reset();
if (!valid){
//System.out.println("la cle n'est plus enregistrée");
}
}
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
Partager