Java監控檔案夾變化

來源:互聯網
上載者:User

 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,爽了!

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.