使用JNotify,你需要做的就是在buildpath中添加jnotify.jar并且放入两个dll文件,例如jnotify.dll jnotify_64bit.dll和jdk的lib文件。一个演示程序是
package jnotify;
import net.contentobjects.jnotify.JNotify;
import net.contentobjects.jnotify.JNotifyListener;
public class MyJNotify {
public void sample() throws Exception {
String path = "Any Folder location here which you want to monitor";
System.out.println(path);
int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED
| JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;
boolean watchSubtree = true;
int watchID = JNotify
.addWatch(path, mask, watchSubtree, new Listener());
Thread.sleep(1000000);
boolean res = JNotify.removeWatch(watchID);
if (!res) {
System.out.println("Invalid");
}
}
class Listener implements JNotifyListener {
public void fileRenamed(int wd, String rootPath, String oldName,
String newName) {
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);
}
}
public static void main(String[] args) {
try {
new MyJNotify().sample();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
IIRC,JNotify需要操作系统特定的DLL。虽然可能不如性能(是的,还不是一个真正的词),JPoller提供了一个纯粹的Java实现。 – 2010-03-15 22:39:50
因此,直到使用Java7时,我总是有点破解,因为我认为Jpoller民意调查很疯狂。 JNotify不是原生的。 – Alfred 2010-03-15 23:02:32
不太确定您的意思是JNotify不是原生的。它确实需要特定于操作系统的DLL /库。 – 2010-03-15 23:04:00