Directory listener in Java

后端 未结 3 1562
名媛妹妹
名媛妹妹 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:19

    Since Java 1.7 you can use the Watch Service API to register for directory events. It is part of Java's New I/O (NIO) library and does not require any additional resources. An example how to use the API can be found in the official documentation.

    After registering the WatchService you can retrieve events for the target path like this:

    for (WatchEvent<?> event: key.pollEvents()) {
                 // Context for directory entry event is the file name of entry
                WatchEvent<Path> ev = cast(event);
                Path name = ev.context();
                Path child = dir.resolve(name);
    
                // print out event
                System.out.format("%s: %s\n", event.kind().name(), child);
            }
    
    0 讨论(0)
  • 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);    }  
            }
    
    0 讨论(0)
  • 2020-11-30 01:39

    You can use JNotify

    JNotify is a java library that allow java application to listen to file system events, such as: File created File modified File renamed File deleted Supported platforms

    Windows (2000 or newer) Windows notes Linux with INofity support (2.6.14 or newer) Linux notes Mac OS X (10.5 or newer) Mac OS notes

    More Info :

    Download JNotify from here

    Extract the zip, put .dll/.so according to platform in your lib path. and create a class provide jnotify-0.93.jar in class path.

    Sample code:

    package org.life.java.stackoverflow.questions;
    
    import net.contentobjects.jnotify.JNotify;
    import net.contentobjects.jnotify.JNotifyListener;
    
    /**
     *
     * @author Jigar
     */
    public class JNotifyDemo {
    
        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);
            }
        }
        public static void main(String[] args) throws Exception {
            new JNotifyDemo().sample();
        }
    }
    

    Output:

    modified C:\Documents and Settings\jigar: LOCALS~1\Temp\etilqs_4s8ywsvyukghK0uDxRop
    modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_4s8ywsvyukghK0uDxRop
    modified C:\Documents and Settings\jigar : LOCALS~1\Temp\output1295531079119
    modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default
    deleted C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001ea9
    created C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eae
    modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom
    modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom
    modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache
    modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eae
    modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eae
    modified C:\Documents and Settings\jigar : LOCALS~1\Temp\output1295531079119
    modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Current Session
    deleted C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001ea8
    created C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eaf
    modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache
    modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom
    modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom
    modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eaf
    modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eaf
    
    0 讨论(0)
提交回复
热议问题