Java监控文件夹变化


1. 线程轮询扫描 
优点:纯java实现,完美跨平台。 
缺点:监听文件较多时,需要扫描的量太大;响应不是非常及时,依赖于扫描间隔时间。 

2. 文件钩子 
优点:事件驱动方式,无目录扫描。 
缺点:跟平台相关 

Jnotify开发包是个不错的文件钩子库,使用方式如下: 
Java代码   收藏代码
  1. public class FieMonitor  
  2. {  
  3.   
  4.     /** 
  5.      * @param args 
  6.      */  
  7.     public static void main(String[] args)  
  8.     {  
  9.         String monitedPath = "E:/templete";  
  10.         int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;  
  11.         // 是否监视子目录  
  12.         boolean watchSubtree = true;   
  13.         try{  
  14.         int watchID = JNotify.addWatch(monitedPath, mask, watchSubtree, new Listener());  
  15.         Thread.sleep(1000000);  
  16.         boolean res = JNotify.removeWatch(watchID);  
  17.         if (!res)  
  18.         {  
  19.             // invalid  
  20.         }  
  21.         }catch(Exception e)  
  22.         {  
  23.             e.printStackTrace();  
  24.         }  
  25.   
  26.     }  
  27.   
  28.     public static class Listener implements JNotifyListener  
  29.     {  
  30.         public void fileRenamed(int wd, String rootPath, String oldName, String newName)  
  31.         {  
  32.             print("renamed " + rootPath + " : " + oldName + " -> " + newName);  
  33.         }  
  34.   
  35.         public void fileModified(int wd, String rootPath, String name)  
  36.         {  
  37.             print("modified " + rootPath + " : " + name);  
  38.         }  
  39.   
  40.         public void fileDeleted(int wd, String rootPath, String name)  
  41.         {  
  42.             print("deleted " + rootPath + " : " + name);  
  43.         }  
  44.   
  45.         public void fileCreated(int wd, String rootPath, String name)  
  46.         {  
  47.             print("created " + rootPath + " : " + name);  
  48.         }  
  49.   
  50.         void print(String msg)  
  51.         {  
  52.             System.err.println(msg);  
  53.         }  
  54.     }  
  55. }  

额外说明:win下面rename一个文件,产生2个事件 rename和 modify 

这个库还有个缺点:要在java.library.path下加入依赖的dll (jnotify.dll/jnotify_64bit.dll),让本人非常不爽。 跟进源码,发现是用的
Java代码   收藏代码
  1. System.loadLibrary("jnotify")  
加载,难怪。遂将其改为 
Java代码   收藏代码
  1. System.load("xxxx/jnotify.dll")  
方式,将dll、so等文件和class文件重新打包成一个jar,爽了!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值