forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirWatcherEx.java
More file actions
53 lines (39 loc) · 1.6 KB
/
DirWatcherEx.java
File metadata and controls
53 lines (39 loc) · 1.6 KB
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
package com.zetcode;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class DirWatcherEx {
public static void main(String[] args) throws IOException {
var watchDir = "C:/Users/Jano/tmp/";
Path filePath = Paths.get(watchDir);
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
// listen for create, delete and modify event kinds
filePath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
WatchKey key;
try {
// the calling thread blocks until a key is signalled
key = watchService.take();
} catch (InterruptedException x) {
return;
}
// retrieve all the accumulated events
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
System.out.printf("Event: %s ", kind.name());
Path path = (Path) event.context();
System.out.printf("Path: %s %n", path.toString());
}
// resetting the key goes back to ready state
key.reset();
}
}
}
}