【问题标题】:Watching directory changes by WatchService in Java 1.7在 Java 1.7 中通过 WatchService 监视目录更改
【发布时间】:2013-11-27 21:50:12
【问题描述】:

从 Java 1.7 开始,有一种方法可以在不添加额外库的情况下查看目录。在 Oracle 网站上,有一个小教程如何使用 WatchService http://docs.oracle.com/javase/tutorial/essential/io/notification.html#try,但我很难理解。没有consitent示例如何使用它。

因此,有人会告诉我如何将侦听器添加到目录并调用方法,例如:f() 当文件添加到目录时让我们说:“./folder”?

【问题讨论】:

    标签: java directory listener watchservice


    【解决方案1】:

    每次您在监视文件夹中创建文件时都会调用这段代码:

        Path path = new File("./folder").toPath();
        WatchService watchService = FileSystems.getDefault().newWatchService();
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
        for (;;) {
            try {
            WatchKey key = watchService.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE)) {
                    System.out.println("file created");
                }
            }
            } catch (InterruptedException x) {
                 return;
            }
        }
    

    【讨论】:

    • 我想为以后的读者补充一下,上面的代码应该粘贴在:neW Thread(new Runnable(){public void run(){HERE}});
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2010-10-20
    相关资源
    最近更新 更多