使用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