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         }
  • 相关阅读:
    【判环】Perpetuum Mobile
    【计算几何】Water Testing
    【动态规划】Überwatch
    【规律】Cunning Friends
    【转载】【最短路Floyd+KM 最佳匹配】hdu 2448 Mining Station on the Sea
    【动态规划】Concerts
    【计算几何】The Queen’s Super-circular Patio
    【规律】Farey Sums
    【规律】Growing Rectangular Spiral
    Mancala II
  • 原文地址:https://www.cnblogs.com/smartisn/p/12846704.html
Copyright © 2011-2022 走看看