【问题标题】:Capture events happening inside a directory捕获目录内发生的事件
【发布时间】:2013-10-30 09:17:27
【问题描述】:

我正在通过以下方法使用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());
}

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

谢谢。

【问题讨论】:

    标签: java watchservice


    【解决方案1】:

    来自the JavaDoc of WatchService

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

    您只调用一次watcher.take()

    要查看更多事件,您必须在使用WatchEvents 后致电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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 这是否捕获了像更改文本文件中的内容这样的事件?
      • 不,它只会检查是否在给定目录中创建或删除了任何新文件
      • 它还会检查是否在子文件夹中创建或删除了任何新文件
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多