動態監控文件和文件夾的Java類庫:JNotify

jopen 10年前發布 | 49K 次閱讀 JNotify Java開發

JNotify,一個支持動態監控文件和文件夾(支持級聯監控)的架包。在linux系統中,調用的是linux底層的inotify服務,只是添加了對 子文件夾級聯監控的功能。在windows中,需要添加附件的dll文件,因為windows默認沒有該服務,這是大拿們自己開發的一個功能。 http://jnotify.sourceforge.net/ 

使用很簡單,以ubuntu系統為例:
1,將jnotify包引入到工程中。
2,將jnotify依賴的so文件加入到java.library.path路徑中。這個變量可能會有多個位置,隨便將jnotify壓縮包中 附帶的libjnotify.so文件加入到其中的任何一個路徑中即可。如果不知道這個變量的值,可以使用 System.getProperty("java.library.path")查看。當然,如果不想這么麻煩,可以在啟動程序時指定JVM的參數

Java代碼  
</div>

  1. -Djava.library.path=你的位置  
</div> ,這樣和上面將so文件加入系統路徑中是一樣的效果。

然后,寫個測試類就可以看見效果了。
 JNotify官網的測試代碼。
 
    public class JnotifyTest {
public static void main(String[] args) {
try {
new JnotifyTest().sample();
} catch (Exception e) {
e.printStackTrace();
}
// System.out.println(System.getProperty("java.library.path"));
}

    public void sample() throws Exception {  
        // path to watch  
        String path = System.getProperty("user.home");  

        // watch mask, specify events you care about,  
        // or JNotify.FILE_ANY for all events.  
        int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED  
                | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;  

        // watch subtree?  
        boolean watchSubtree = true;  

        // add actual watch  
        int watchID = JNotify  
                .addWatch(path, mask, watchSubtree, new Listener());  

        // sleep a little, the application will exit if you  
        // don't (watching is asynchronous), depending on your  
        // application, this may not be required  
        Thread.sleep(1000000);  

        // to remove watch the watch  
        boolean res = JNotify.removeWatch(watchID);  
        if (!res) {  
            // invalid watch ID specified.  
        }  
    }  

        //可以在下面的監控方法中添加自己的代碼。比如在fileModified中添加重新加載配置文件的代碼  
    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);  
        }  

    }  
}  </pre><br />


在實際的使用過程中,如果是web工程,我的習慣是添加一個listener監聽器,當監聽器初始化時,添加對指定文件或文件夾的監控。這樣我們就不必為每次修改了配置文件都需要重啟工程而苦惱了。如果是Java工程,就是需要的地方添加監控吧。

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!