1

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

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

谢谢你。

4

2 回答 2

5

JavaDoc 的WatchService

一个 Watchable 对象通过调用它的 register 方法注册到一个 watch 服务,返回一个 WatchKey 来表示注册。当检测到对象的事件时,会发出键信号,如果当前未发出信号,则将其排队到监视服务,以便调用 poll 或 take 方法以检索键和处理事件的消费者可以检索它。处理完事件后,消费者调用密钥的重置方法来重置密钥,这允许向密钥发出信号并与进一步的事件一起重新排队。

你只调用watcher.take()一次。

要查看更多事件,您必须watchKey.reset()在使用WatchEvents 后调用。将所有这些放在一个循环中。

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

另请查看Java 教程的相关部分

于 2013-10-30T09:29:42.297 回答
3

使用 Apache Commons IO File Monitoring
它也将捕获子文件夹中发生的事件

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();
    }
}
于 2013-10-30T10:27:05.930 回答