/
FileMonitor.java
39 lines (34 loc) · 961 Bytes
/
FileMonitor.java
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
package learn.java.nio.path;
import java.io.IOException;
import java.nio.file.FileSystems;
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;
/**
* 文件修改通知,消息机制非轮询
* @author wzt
*
*/
public class FileMonitor {
public static void main(String[] args) {
boolean shutdown=false;
try {
WatchService watcher=FileSystems.getDefault().newWatchService();
Path path=FileSystems.getDefault().getPath(".");
WatchKey key=path.register(watcher,StandardWatchEventKinds.ENTRY_MODIFY);
while(!shutdown){
key=watcher.take();
for(WatchEvent<?> event:key.pollEvents()){
if(event.kind()==StandardWatchEventKinds.ENTRY_MODIFY){
System.out.println("data1 is modified");
}
}
key.reset();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}