码迷,mamicode.com
首页 > 编程语言 > 详细

关于java一些零零散散的点(三)

时间:2019-08-25 20:09:01      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:cto   creat   tps   com   files   comment   rac   def   删除   

原文引用https://www.dazhuanlan.com/2019/08/25/5d625ec2c8207/


直接上代码

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
Path path = Paths.get("path"); 
if (Files.exists(path)) {
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
path.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE
);
while (true) {
WatchKey key = watchService.take(); // 阻塞
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path file = ev.context(); // 得到事件中的文档

if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
// 创建时
}

if (StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind())) {
// 修改时
}

if (StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind())) {
// 删除时
}
}
key.reset(); // 处理成功后清除队列中的key,否则后续事件无法触发
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}

一些注意点

  • 不支持注册单个文档的监控,若path不是文档夹则会抛出java.nio.file.NotDirectoryException

关于java一些零零散散的点(三)

标签:cto   creat   tps   com   files   comment   rac   def   删除   

原文地址:https://www.cnblogs.com/petewell/p/11408897.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!