Java监控文件变化

NIO.2的Path类提供了如下的一个方法来监听文件系统的变化。

register(WatcherService watcher,WatchEvent.Kind<?>... events):用watcher监听该path代表的目录下文件变化。event参数指定要监听哪些类型的事件。

WatchService有三个方法来监听目录的文件变化事件。

WatchKey poll():获取下一个WatchKey,如果没有WatchKey发生就立即返回null;

WatcheKey poll(long timeout,TimeUnit unit):尝试等待timeout时间去获取下一个WatchKey;

WatchKey  take():获取下一个WatchKey,如果没有发生就一直等待;

如果程序需要一直监控,则应该选择使用take()方法,如果程序只需要监控指定时间,则使用poll方法。

  1. import java.nio.file.FileSystems;  
  2. import java.nio.file.Paths;  
  3. import java.nio.file.StandardWatchEventKinds;  
  4. import java.nio.file.WatchEvent;  
  5. import java.nio.file.WatchKey;  
  6. import java.nio.file.WatchService;  
  7. public class Test {  
  8.     public static void main(String[] args) throws Exception  
  9.     {  
  10.           
  11.         WatchService watchService=FileSystems.getDefault().newWatchService();  
  12.         Paths.get("C:/").register(watchService,   
  13.                 StandardWatchEventKinds.ENTRY_CREATE,  
  14.                 StandardWatchEventKinds.ENTRY_DELETE,  
  15.                 StandardWatchEventKinds.ENTRY_MODIFY);  
  16.         while(true)  
  17.         {  
  18.             WatchKey key=watchService.take();  
  19.             for(WatchEvent<?> event:key.pollEvents())  
  20.             {  
  21.                 System.out.println(event.context()+"发生了"+event.kind()+"事件");  
  22.             }  
  23.             if(!key.reset())  
  24.             {  
  25.                 break;  
  26.             }  
  27.         }  
  28.     }  
  29. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值