捕获目录内发生的事件

时间:2013-10-30 09:17:27

标签: java watchservice

我使用Java 7 nio WatchService使用以下方法观看目录。

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

但是上述方法只响应一个事件发生在目录中,之后观察者没有响应该文件夹中发生的事件。有没有办法可以修改它来捕获文件夹内发生的所有事件。我也想修改它来捕获子文件夹中发生的事件。有人可以帮我这个。

谢谢。

2 个答案:

答案 0 :(得分:5)

来自the JavaDoc of WatchService

  

Watchable对象通过调用其register方法向watch服务注册,返回WatchKey来表示注册。当检测到对象的事件时,发信号通知密钥,如果当前未发信号,则将其排队到监视服务,以便调用该轮询的消费者可以检索该密钥,或者采取方法来检索密钥和处理事件。一旦事件被处理完毕,消费者就会调用密钥的重置方法来重置密钥,该密钥允许密钥发出信号并与其他事件一起重新排队。

您只需拨打watcher.take()一次。

要观看更多活动,您必须在使用WatchEvent后致电watchKey.reset()。将所有这些放在一个循环中。

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

另请查看the relevant section of the Java Tutorial

答案 1 :(得分:1)

使用Apache Commons IO文件监控
它还将捕获子文件夹中发生的事件

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