Directory listener in Java

后端 未结 3 1574
名媛妹妹
名媛妹妹 2020-11-30 00:45

I have an application in which I want to listen to any changes made to a particular directory. The application should ping me as soon as there are any files added, deleted

3条回答
  •  遥遥无期
    2020-11-30 01:36

    Jnotify for file notification in java. Code sample

       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.    
                }  
            }  
        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);    }  
            }
    

提交回复
热议问题