OnJava8-Examples/files/TreeWatcher.java

54 lines
1.5 KiB
Java
Raw Normal View History

2015-12-06 11:45:16 -08:00
// files/TreeWatcher.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-12-06 11:45:16 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-12-06 11:45:16 -08:00
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import java.util.concurrent.*;
public class TreeWatcher {
static void watchDir(Path dir) {
try {
WatchService watcher =
FileSystems.getDefault().newWatchService();
dir.register(watcher, ENTRY_DELETE);
Executors.newSingleThreadExecutor().submit(() -> {
try {
WatchKey key = watcher.take();
for(WatchEvent evt : key.pollEvents()) {
System.out.println(
"evt.context(): " + evt.context() +
"\nevt.count(): " + evt.count() +
"\nevt.kind(): " + evt.kind());
System.exit(0);
}
} catch(InterruptedException e) {
return;
}
});
} catch(IOException e) {
throw new RuntimeException(e);
}
}
2016-01-25 18:05:55 -08:00
public static void
main(String[] args) throws Exception {
2015-12-06 11:45:16 -08:00
Directories.refreshTestDir();
Directories.populateTestDir();
Files.walk(Paths.get("test"))
.filter(Files::isDirectory)
.forEach(TreeWatcher::watchDir);
PathWatcher.delTxtFiles();
}
}
/* Output:
2015-12-15 11:47:04 -08:00
deleting test\bag\foo\bar\baz\File.txt
2016-07-22 14:45:35 -06:00
deleting test\bar\baz\bag\foo\File.txt
2015-12-06 11:45:16 -08:00
evt.context(): File.txt
evt.count(): 1
evt.kind(): ENTRY_DELETE
2016-07-27 11:12:11 -06:00
evt.context(): File.txt
evt.count(): 1
evt.kind(): ENTRY_DELETE
2015-12-06 11:45:16 -08:00
*/