• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
bigming
博客园    首页    新随笔    联系   管理    订阅  订阅

WatchDirService 实时监控

 1 import config.Config;
 2 
 3 import java.io.IOException;
 4 import java.nio.file.*;
 5 import java.util.List;
 6 import java.util.concurrent.TimeUnit;
 7 
 8 /**
 9  * Created by jason on 2017/2/14.
10  */
11 public class WatchDirService {
12     private WatchService watchService;
13     private boolean notDone = true;
14 
15     public WatchDirService(String dirPath){
16         init(dirPath);
17     }
18 
19     private void init(String dirPath) {
20         Path path = Paths.get(dirPath);
21         try {
22             watchService = FileSystems.getDefault().newWatchService();
23             path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.ENTRY_DELETE);
24         } catch (IOException e) {
25             e.printStackTrace();
26         }
27     }
28 
29     public void start(){
30         System.out.print("watch...");
31         while (notDone){
32             try {
33                 WatchKey watchKey = watchService.poll(Config.POLL_TIME_OUT, TimeUnit.SECONDS);
34                 System.out.print("change");
35                 if(watchKey != null){
36                     List<WatchEvent<?>> events = watchKey.pollEvents();
37                     for (WatchEvent event : events){
38                         WatchEvent.Kind<?> kind = event.kind();
39                         if (kind == StandardWatchEventKinds.OVERFLOW){
40                             continue;
41                         }
42                         WatchEvent<Path> ev = event;
43                         Path path = ev.context();
44                         if(kind == StandardWatchEventKinds.ENTRY_CREATE){
45                             System.out.println("create " + path.getFileName());
46                         }else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
47                             System.out.println("modify " + path.getFileName());
48                         }else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
49                             System.out.println("delete " + path.getFileName());
50                         }
51                     }
52                     if(!watchKey.reset()){
53                         System.out.println("exit watch server");
54                         break;
55                     }
56                 }
57             } catch (InterruptedException e) {
58                 e.printStackTrace();
59                 return;
60             }
61         }
62     }
63 }

 

posted @ 2019-01-29 16:45  bigming  阅读(415)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3