1. 線程輪詢掃描
優點:純java實現,完美跨平台。
缺點:監聽檔案較多時,需要掃描的量太大;響應不是非常及時,依賴於掃描間隔時間。
2. 檔案鉤子
優點:事件驅動方式,無目錄掃描。
缺點:跟平台相關
Jnotify開發包是個不錯的檔案鉤子庫,使用方式如下:
public class FieMonitor
{
/**
* @param args
*/
public static void main(String[] args)
{
String monitedPath = "E:/templete";
int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;
// 是否監視子目錄
boolean watchSubtree = true;
try{
int watchID = JNotify.addWatch(monitedPath, mask, watchSubtree, new Listener());
Thread.sleep(1000000);
boolean res = JNotify.removeWatch(watchID);
if (!res)
{
// invalid
}
}catch(Exception e)
{
e.printStackTrace();
}
}
public static 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);
}
}
}
額外說明:win下面rename一個檔案,產生2個事件 rename和 modify
這個庫還有個缺點:要在java.library.path下加入依賴的dll (jnotify.dll/jnotify_64bit.dll),讓本人非常不爽。 跟進源碼,發現是用的
System.loadLibrary("jnotify")
載入,難怪。遂將其改為 System.load("xxxx/jnotify.dll") 方式,將dll、so等檔案和class檔案重新打包成一個jar,爽了!