java本身不能直接监听系统的文件操作事件,但可以用第三方开源软件监控。
在这里介绍JNotify 大家可以在sourceforge上去下载。说说用法,其实真的好简单代码如下
1.下载成功后,把jnotify.dll放到system32下面,不然就会报错Exception in thread “main” java.lang.UnsatisfiedLinkError: no jnotify in java.library.path
2.写一个类implements JNotifyListener,
public class JnotifyListener implements JNotifyListener { @Override public void fileCreated(int arg0, String arg1, String arg2) { System.out.println("fileCreate path:" + arg1); System.out.println("fileCreate name:" + arg2); } @Override public void fileDeleted(int arg0, String arg1, String arg2) { System.out.println("fileDeleted path:" + arg1); System.out.println("fileDeleted name :" + arg2); } @Override public void fileModified(int arg0, String arg1, String arg2) { System.out.println("fileModified path:" + arg1); System.out.println("fileModified name:" + arg2); } @Override public void fileRenamed(int arg0, String arg1, String arg2, String arg3) { System.out.println("fileRenamed path:" + arg1); System.out.println("fileRenamedname:" + arg2); } }
然后写个测试类
public class TestJnotify { public static void main(String[] args) throws JNotifyException { int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED |JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED; JNotify.addWatch("e:/testListener", mask, true, new JnotifyListener()); for (;;) { } } }
这样就可以实现监视目录变化了
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10351.html