How can I watch subdirectory for changes with WatchService? (Java)

后端 未结 2 2161
花落未央
花落未央 2020-12-31 15:49

I want to watch some directory for changes and her subdirectories. I tried to do this with WatchService but I can\'t know from which directory the file was changed. How can

2条回答
  •  鱼传尺愫
    2020-12-31 16:13

    Generally you provide the directory name of the file when starting the watchservice. Here is a tutorial demonstrating how that works:

    http://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes

    From the tutorial:

       Path dir = ...;
       try {
           WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
       }[.....]
    

    when you catch a notification:

       //The filename is the context of the event.
       WatchEvent ev = (WatchEvent)event;
       Path filename = ev.context();
    
       Path child = dir.resolve(filename);
    

提交回复
热议问题