Capture events happening inside a directory

余生长醉 提交于 2020-01-30 02:58:53

问题


Im watching a directory using Java 7 nio WatchService by using below method.

Path myDir = Paths.get("/rootDir");

try {
  WatchService watcher = myDir.getFileSystem().newWatchService();
  myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, 
  StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

  WatchKey watckKey = watcher.take();

  List<WatchEvent<?>> events = watckKey.pollEvents();
  for (WatchEvent event : events) {
    if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
      System.out.println("Created: " + event.context().toString());
      JOptionPane.showMessageDialog(null,"Created: " + event.context().toString());
    }
    if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
      System.out.println("Delete: " + event.context().toString());
      JOptionPane.showMessageDialog(null,"Delete: " + event.context().toString());
    }
    if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
      System.out.println("Modify: " + event.context().toString());
      JOptionPane.showMessageDialog(null,"Modify: " + event.context().toString());
    }
  }

} catch (Exception e) {
  System.out.println("Error: " + e.toString());
}

But the above method only respond in one events happen in the directory after that watcher does not respond to the events happen in that folder. Is there a way that I can modify this to capture all events happen inside the folder. I also want to modify this to capture events happen in sub folders too. Can someone help me with that.

Thank you.


回答1:


Use Apache Commons IO File Monitoring
it will also capture events happening in sub folders too

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class Monitor {

    public Monitor() {

    }

    //path to a folder you are monitoring .

    public static final String FOLDER = MYPATH;


    public static void main(String[] args) throws Exception {
        System.out.println("monitoring started");
        // The monitor will perform polling on the folder every 5 seconds
        final long pollingInterval = 5 * 1000;

        File folder = new File(FOLDER);

        if (!folder.exists()) {
            // Test to see if monitored folder exists
            throw new RuntimeException("Directory not found: " + FOLDER);
        }

        FileAlterationObserver observer = new FileAlterationObserver(folder);
        FileAlterationMonitor monitor =
                new FileAlterationMonitor(pollingInterval);
        FileAlterationListener listener = new FileAlterationListenerAdaptor() {
            // Is triggered when a file is created in the monitored folder
            @Override
            public void onFileCreate(File file) {

                    // "file" is the reference to the newly created file
                    System.out.println("File created: "+ file.getCanonicalPath());


            }

            // Is triggered when a file is deleted from the monitored folder
            @Override
            public void onFileDelete(File file) {
                try {
                    // "file" is the reference to the removed file
                    System.out.println("File removed: "+ file.getCanonicalPath());
                    // "file" does not exists anymore in the location
                    System.out.println("File still exists in location: "+ file.exists());
                } catch (IOException e) {
                    e.printStackTrace(System.err);
                }
            }
        };

        observer.addListener(listener);
        monitor.addObserver(observer);
        monitor.start();
    }
}



回答2:


From the JavaDoc of WatchService:

A Watchable object is registered with a watch service by invoking its register method, returning a WatchKey to represent the registration. When an event for an object is detected the key is signalled, and if not currently signalled, it is queued to the watch service so that it can be retrieved by consumers that invoke the poll or take methods to retrieve keys and process events. Once the events have been processed the consumer invokes the key's reset method to reset the key which allows the key to be signalled and re-queued with further events.

You are only calling watcher.take() once.

To watch for further events, you must call watchKey.reset() after consuming the WatchEvents. Put all this in a loop.

while (true) {
  WatchKey watckKey = watcher.take();
  List<WatchEvent<?>> events = watckKey.pollEvents();
  for (WatchEvent event : events) {
    // process event
  }
  watchKey.reset();
}

Also take a look at the relevant section of the Java Tutorial.



来源:https://stackoverflow.com/questions/19678170/capture-events-happening-inside-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!