首页 > 编程语言 > 详细

JAVA实时监控指定文件夹 创建文件,修改文件,删除文件

时间:2020-05-08 00:18:51      阅读:155      评论:0      收藏:0      [点我收藏+]

话不多说,直接上代码:

 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实时监控指定文件夹 创建文件,修改文件,删除文件

原文:https://www.cnblogs.com/smartisn/p/12846704.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!