在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);
}
}
---------------------------法典-------------------------------
您可以将多个目录注册到同一个目录观察程序。取决于子目录的创建方式。如果该目录已存在,则可以使用 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);
}