-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathjava-file-WatchService.java
More file actions
103 lines (93 loc) · 2.97 KB
/
java-file-WatchService.java
File metadata and controls
103 lines (93 loc) · 2.97 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
-----------------------
文件监视 |
-----------------------
# 监视某个目录
* 文件创建
* 删除
* 修改
-----------------------
Demo |
-----------------------
//WatchService 是线程安全的,跟踪文件事件的服务,一般是用独立线程启动跟踪
public static void watchRNDir(Path path) throws Exception {
//创建 WatchService 对象
WatchService watchService = FileSystems.getDefault().newWatchService();
//给path路径加上文件观察服务
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
// 开始监视路径
while (true) {
//线程阻塞
final WatchKey key = watchService.take();
//获取事件集合
List<WatchEvent<?>> watchEventList = key.pollEvents();
//遍历
for (WatchEvent<?> watchEvent : watchEventList) {
// 获取事件
final WatchEvent.Kind<?> kind = watchEvent.kind();
// handle OVERFLOW event
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
//创建事件
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
}
//修改事件
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
}
//删除事件
if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
}
//把当前事件强制转换泛型为 Path 的事件
final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
//获取事件文件名称
final Path filename = watchEventPath.context();
// print it out
System.out.println(kind + " -> " + filename);
}
// reset the keyf
boolean valid = key.reset();
// exit loop if the key is not valid (if the directory was
// deleted, for
if (!valid) {
break;
}
}
}
------------------------------------
WatchService |
------------------------------------
# 构建
WatchService watchService = FileSystems.getDefault().newWatchService();
# 方法
WatchKey take();
* 检索并移除下一个watch key。若没有可检索的则阻塞。
------------------------------------
WatchKey |
------------------------------------
# 构建
通过 WatchService 实例的 take()方法获取
# 方法
List<WatchEvent<?>> pollEvents();
* 检索并移除所有该watch key
------------------------------------
WatchEvent |
------------------------------------
# 构建
# 方法
Kind<?> kind();
* 返回事件种类
------------------------------------
Kind |
------------------------------------
# 方法
String name();
* 返回事件的名称
------------------------------------
StandardWatchEventKinds |
------------------------------------
# 事件类
# 静态字段
OVERFLOW
ENTRY_CREATE
ENTRY_DELETE
ENTRY_MODIFY