项目需求,监控文件夹下,文件的变更。 — JNotify
JNotify,跨平台,支持Linux,win32, win64,mac
原理:略。
下载地址:去sourceforge下载
使用方法:
[1]下载JNotify包, 里面有linux,windows,mac平台,所使用的包。其中windows平台使用dll文件,linux平台使用so结尾的文件
[2]以windows平台为例。建javase项目。
[3]引入JNotify.jar包
[4]将JNotify.dll文件,放在电脑随便某个目录下,例如 c:/mydll/JNotify.dll
[5]告诉程序,在执行程序时,去哪里调用dll文件(linux下是so文件)。
方法,右键项目,debug as — > debug configuration
[6]建第一个类,作为主程序
package me.demo;
import net.contentobjects.jnotify.JNotify;
import net.contentobjects.jnotify.JNotifyException;
public class JNotifyTest {
public static void main(String[] args) {
System.err.println(System.getProperty("java.library.path"));
System.err.println("开始监听目录下内容......");
try {
JNotifyTest.sample();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* JNotify监控方法
* @throws JNotifyException
* @throws InterruptedException
*/
private static void sample() throws JNotifyException, InterruptedException {
//要监控哪个目录
String path = "/var/alldata/";
//监控用户的操作,增,删,改,重命名
int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED ;
//是否监控子目录
boolean subTree = true;
//开始监控
int watchID = JNotify.addWatch(path, mask, subTree, new MyJNotifyListener());
//睡一会,看看效果
Thread.sleep(1000 * 60 * 3);
//停止监控
boolean res = JNotify.removeWatch(watchID);
if (res) {
System.err.println("已停止监听");
}
System.err.println(path);
}
// public static class Listener implements JNotifyListener{
// @Override
// public void fileCreated(int wd, String rootPath, String name) {
// System.err.println("create: --->" + wd + "--->" + rootPath + "--->" + name);
// }
// @Override
// public void fileDeleted(int wd, String rootPath, String name) {
// System.err.println("create: --->" + wd + "--->" + rootPath + "--->" + name);
// }
// @Override
// public void fileModified(int wd, String rootPath, String name) {
// System.err.println("create: --->" + wd + "--->" + rootPath + "--->" + name);
// }
// @Override
// public void fileRenamed(int wd, String rootPath, String oldName, String newName) {
// System.err.println("create: --->" + wd + "--->" + rootPath + "--->" + oldName + "--->" + newName);
// }
// }
}
[7]建第二个类,实现JNotifyListener接口。这个类作用就是,检测到目录修改后,要做哪些动作。
package me.demo;
import net.contentobjects.jnotify.JNotifyListener;
public class MyJNotifyListener implements JNotifyListener{
@Override
public void fileCreated(int wd, String rootPath, String name) {
System.err.println("create: --->" + wd + "--->" + rootPath + "--->" + name);
}
@Override
public void fileDeleted(int wd, String rootPath, String name) {
System.err.println("delete: --->" + wd + "--->" + rootPath + "--->" + name);
}
@Override
public void fileModified(int wd, String rootPath, String name) {
System.err.println("modified: --->" + wd + "--->" + rootPath + "--->" + name);
}
@Override
public void fileRenamed(int wd, String rootPath, String oldName, String newName) {
System.err.println("rename: --->" + wd + "--->" + rootPath + "--->" + oldName + "--->" + newName);
}
}
[8]测试。