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