在JAVA中使用WatchService。我可以同时观看子目录吗?

时间:2014-11-16 08:19:13

标签: java watchservice

在JAVA中,我将使用WatchService查看目录。

例如,如果我观察/ users / monitor,WatchService只能观看一个目录。

但我想同时看“每个子目录”

watch /users/monitor
/users/monitor/a
/users/monitor/b
...

我该如何编码? T_T

---------------------------代码------------------- ------------

package testpack;

import java.nio.file.*;
import java.util.List;
import java.io.*;

class DirectoryFilter implements FileFilter {
    public boolean accept(File file) {
        return file.isDirectory();
    }
}

public class DirectoryWatchExample {
    public static void testForDirectoryChange(Path myDir) {
        while (true) {
            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());
                    }
                    if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                        System.out.println("Delete: "
                                + event.context().toString());
                    }
                    if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                        System.out.println("Modify: "
                                + event.context().toString());
                    }
                }

            } catch (Exception e) {
                System.out.println("Error: " + e.toString());
            }
        }
    }

    public static void main(String[] args) {
        Path myDir = Paths.get("/users/heejoongkim/monitor");
        // define a folder root
        System.out.println("Monitor Start");
        File dir = new File("/users/heejoongkim/monitor");
        testForDirectoryChange(myDir);
    }
}

---------------------------代码------------------- ------------

1 个答案:

答案 0 :(得分:0)

您可以将多个目录注册到同一目录观察程序。取决于子目录的创建方式。如果目录已经存在,您可以使用File.listFiles进行循环,并将每个目录注册到同一个观察者。

如果在观察者注册后创建文件,您可以执行以下操作:enter code here

for (WatchEvent<?> event: key.pollEvents()) 
            {
                WatchEvent.Kind<?> kind = event.kind();
                WatchEvent<Path> ev = (WatchEvent<Path>)event;                    
                Path filename = ev.context();

                Path child = dir.resolve(filename);
                if(child.toFile().isDirectory() && ev.kind() == ENTRY_CREATE )
                {
                    child.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
                }
                System.out.println(child);
            }