zoukankan      html  css  js  c++  java
  • JAVA实时监控指定文件夹 创建文件,修改文件,删除文件

    话不多说,直接上代码:

     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         }
  • 相关阅读:
    技术分享的一些好的建议
    项目经理排期的几个tip
    公司的目标和你的目标的关系
    Android实现双击事件的两种方式
    互联网公司团队建设的几个要点
    一对一还是一对多? MVP设计前提
    互联网产品研发的典型流程
    架构和模式的区别:三层架构和MVC在应用开发中的位置
    Android Studio插件:PlantUML
    Android Studio插件:GsonFromat
  • 原文地址:https://www.cnblogs.com/smartisn/p/12846704.html
Copyright © 2011-2022 走看看