要想更好的了解jnotify,我们可以事先了解一下jni。
jni实现了java与其它语言的通信(主要是c&c++),当java调c语言中间要经过类型转换等,例如c语言中没有string类型的数据,这时我们使用jni就可以解决这个问题了。
使用jnotify完成监测windows中某个文件夹里的文件的状态:
创建一个java工程,将jnotify 的jar包导进来
代码如下:
public class MonitorFile extends JNotifyAdapter {
public static void main(String[] args) {
System.err.println(System.getProperty("java.library.path"));
System.err.println("开始监听目录下内容......");
try {
MonitorFile.sample();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* JNotify监控方法
*
* @throws JNotifyException
* @throws InterruptedException
*/
private static void sample() throws JNotifyException, InterruptedException {
// 要监控哪个目录
String path = "F:/test";
// 监控用户的操作,增,删,改,重命名
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 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);
}
}
当我们完成代码之后运行会报main方法有错,此时我们将这两个文件拷贝到jre的bin文件夹中就可以了。
实际调用原理是先找到jdk下面的这两个dll文件,然后找到的是windows里面的dll文件。如第二张图
下载文件地址 :https://sourceforge.net/projects/jnotify/?source=typ_redirect
使用jnotify完成监测linux系统中某个文件夹里的文件的状态:
http://jnotify.sourceforge.net/在此地址中可以看到有windows和linux系统的不同文件,这时我们下载linux系统下的文件就可以了。