当前位置: 首页 > 面试题库 >

捕获目录中发生的事件

陶富
2023-03-14
问题内容

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

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

谢谢。


问题答案:

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


 类似资料:
  • 问题内容: 我有一个用jQuery 方法动态生成的with : 包含一些输入元素,它们被加载到modal中。 使用jQuery的方法,我可以在事件触发后捕获输入值,但是当将元素动态添加到模式div时,当用户输入文本时事件不会触发。 哪种jQuery方法支持处理由动态创建的元素触发的事件? 用于创建新输入元素的代码为: 捕获用户值的代码是: 第二个代码块似乎适用于原始元素,但不会由新的动态生成的元素

  • 简单场景-ScrollView托管一个具有多个子元素的LinearLayout,这是在Android上开发支持滚动的视图的首选模式。 我需要捕获onScrollEvents,启动,停止等。如果我使用ListView/onScrollListener组合,它们很容易获得并且工作得很好。 用于滚动视图的专用小部件是否具有捕获这些事件的内置功能?加油!我尝试过 OnTouchEvent 听众,onGes

  • 本文向大家介绍浅谈javascript中的事件冒泡和事件捕获,包括了浅谈javascript中的事件冒泡和事件捕获的使用技巧和注意事项,需要的朋友参考一下 1.事件冒泡   IE 的事件流叫做事件冒泡(event bubbling),即事件开始时由最具体的元素(文档中嵌套层次最深的那个节点)接收,然后逐级向上传播到较为不具体的节点(文档)。以下面的HTML 页面为例: 如果你单击了页面中的<div

  • 如果您有这样的字符串: < code >【hello world】这是【最好的。家]是个好地方。 如何仅提取括号[]中的每个单词(由空格分隔)。现在我有这个工作 https://regex101.com/r/Tgokeq/2 哪个返回: 你好世界 最好的。家 但我想要: 你好 世界 该 最好的 。主页 PS:我知道我可以在一个foreach中做字符串拆分,但我不想要在正则表达式本身中使用它,就像这

  • 问题内容: 我希望这将是一件简单的事情,但是我找不到任何能够做到这一点的东西。 我只想获取给定文件夹/目录中的所有文件夹/目录。 因此,例如: 我希望得到一个数组: 或者上面的路径,如果那是它的服务方式… 那么已经有什么可以做以上的事情吗? 问题答案: 这是此答案的较短的同步版本,它可以列出当前目录中的所有目录(是否隐藏): 节点10.10.0+的更新 我们可以使用的新选项来跳过额外的通话:

  • 问题内容: 我在Java中有一个应用程序,其中我尝试确保如果有人在代码中退出代码System.exit(),则应调用侦听器来执行某些操作,例如记录消息并释放资源… 我如何实施它,欢迎任何建议/方法。 问题答案: 该方法可用于添加一个关闭钩子,该钩子基本上是未启动的,该钩子在Java虚拟机关闭时执行。 但是,这是应该谨慎对待的领域,因为它是在JVM生命周期的非常敏感的时间执行的。从API规范中获取该