话不多说,直接上代码:
1 package com.python;
2 import java.nio.file.FileSystems;
3 import java.nio.file.Path;
4 import java.nio.file.Paths;
5 import java.nio.file.StandardWatchEventKinds;
6 import java.nio.file.WatchEvent;
7 import java.nio.file.WatchKey;
8 import java.nio.file.WatchService;
9 public class Watch {
10 public static void main(String[] args) {
11 try{
12
13 //创建一个监听服务
14 WatchService service=FileSystems.getDefault().newWatchService();
15 //设置路径
16 Path path=Paths.get("D:\\ATEST");
17 //注册监听器
18 path.register(service, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
19
20 WatchKey watchKey;
21
22 //使用dowhile
23 do{
24 //获取一个watch key
25 watchKey=service.take();
26 for(WatchEvent> event:watchKey.pollEvents()){
27 //如果时间列表不为空,打印事件内容
28 WatchEvent.Kind> kind=event.kind();
29 Path eventPath=(Path)event.context();
30 System.out.println(eventPath+":"+kind+":"+eventPath);
31
32 }
33 System.out.println("目录内容发生改变");
34
35 }while(watchKey.reset());
36 }catch(Exception e){
37 e.printStackTrace();
38
39 }
40
41 // 1、通过FileSystems.getDefault().newWatchService()创建一个监听服务;
42 // 2、设置路径;
43 // 3、对目录注册一个监听器;
44 // 4、之后进入循环,等待watch key;
45 // 5、此时如果有事件发生可通过watchkey的pollevent()方法获取;
46 // 6、之后可以对event处理;
47 }
48 }
标签:文件,java,nio,Path,文件夹,file,import,JAVA,event
来源: https://www.cnblogs.com/smartisn/p/12846704.html