2

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

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

4

1 回答 1

0

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

如果文件是在观察者注册后创建的,您可以执行以下操作。

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);
            }
于 2015-06-30T22:20:00.980 回答