下载链接: http://jnotify.sourceforge.net/index.html官网地址
解压 吧dll文件放入jre bin 目录(linux )
linux放这个
导入坐标
<dependency>
<groupId>net.contentobjects.jnotify</groupId>
<artifactId>jnotify</artifactId>
<version>0.94</version>
</dependency>
实现对文件目录的监听
import java.io.File;
import net.contentobjects.jnotify.JNotify;
public class FileNotify {
public static void notify(String filepath) throws Exception {
if (!new File(filepath).exists()) {
System.out.println("文件目录不存在");
return;
}
// 定义你所需要检测的事件类型,或者是全部FILE_ANY
int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;
int mask1 =JNotify.FILE_ANY;
// 是否检测子目录
boolean watchSubtree = true;
// 添加监听
int watchID = JNotify.addWatch(filepath, mask, watchSubtree, new Listener());
System.out.println(watchID);
// 定义监听持续时间,此处是死循环,所以是时刻监听
// while(true) {
// Thread.sleep(1000*60);
// }
// 定义监听时间,如果超过这个时间,程序会退出;如果不定义就得不到监听
Thread.sleep(1000*60);//60秒
//移除监听
boolean res = JNotify.removeWatch(watchID);
if (!res) {
// invalid watch ID specified.
}
}
public static void main(String[] args) {
String path ="F:\\Pm25";
System.out.println(path);
try {
notify(path);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
监听事件的处理
class Listener implements JNotifyListener {
public void fileRenamed(int wd, String rootPath, String oldName, String newName) {
System.out.println(wd);
System.out.println(rootPath);
print("renamed " + rootPath + " : " + oldName + " -> " + newName);
}
public void fileModified(int wd, String rootPath, String name) {
print("modified " + rootPath + " : " + name);
}
public void fileDeleted(int wd, String rootPath, String name) {
print("deleted " + rootPath + " : " + name);
}
public void fileCreated(int wd, String rootPath, String name) {
print("created " + rootPath + " : " + name);
}
void print(String msg) {
System.err.println(msg);
}
}