How to detect filesystem has changed in java

前端 未结 4 1884
生来不讨喜
生来不讨喜 2021-01-13 21:34

I would like to know how to efficiently implement filesystem changes in java? Say I got a file in a folder and modify that file. I would like to be notified by java about th

相关标签:
4条回答
  • 2021-01-13 21:40

    Take a look at JNotify, which performs this type of monitoring.

    Java 7 will have some more advanced APIs (WatchService) for this sort of work which will eliminate polling on the OSes that support this.

    0 讨论(0)
  • 2021-01-13 21:51

    There is an Apache package that does file system monitoring: commons.io.monitor.

    Documentation

    An example

    From what I can tell, you will still need to poll albeit you have control over the frequency.

    0 讨论(0)
  • 2021-01-13 22:01

    I doubt that there is a pure java way to do this. Operating systems offer APIs to monitor file system a activity. You will probably need to call those APIs.

    0 讨论(0)
  • 2021-01-13 22:06

    Use JNotify, All you need to do is add jnotify.jar in buildpath and put two dll files i.e jnotify.dll jnotify_64bit.dll and inside lib of jdk. A demo program is

    package jnotify;
    
    import net.contentobjects.jnotify.JNotify;
    import net.contentobjects.jnotify.JNotifyListener;
    
    public class MyJNotify {
      public void sample() throws Exception {
        String path = "Any Folder location here which you want to monitor";
        System.out.println(path);
        int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED
                | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;
        boolean watchSubtree = true;
        int watchID = JNotify
                .addWatch(path, mask, watchSubtree, new Listener());
        Thread.sleep(1000000);
        boolean res = JNotify.removeWatch(watchID);
        if (!res) {
            System.out.println("Invalid");
        }
    }
    
    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) {
        try {
            new MyJNotify().sample();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    }
    
    0 讨论(0)
提交回复
热议问题