我试图在客户端和服务器之间同步两个文件夹及其子目录。我有this class的修改版本,我在下面发布了这个版本。在我的Client类中,我创建了一个WatchDir对象,并在无限循环中调用其processEvents()方法。如果事件已注册,则该方法返回myTuple对象(包含事件类型和路径对象的结构),否则返回null。问题是,这似乎只适用于目录中发生的第一个事件(即,如果我将文件添加到监视文件夹,我的WatchDir object.processEvents()将返回一个带有ENTRY_CREATE事件的元组,并且永远不会返回另一个Tuple之后发生的其他文件添加/删除/修改)。我希望在每次发生某些事件时连续调用processEvents(因此无限时)返回一个元组。谢谢你的帮助!
我修改过的WatchDir:
import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.LinkOption.*;
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class WatchDir {
private final WatchService watcher;
private final Map<WatchKey,Path> keys;
private final boolean recursive;
private boolean trace = false;
public WatchDir(Path dir, boolean recursive) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<WatchKey,Path>(); //holds the key for each subdirectory
this.recursive = true;
registerAll(dir);
}
public void registerAll(Path start) throws IOException {
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
register(dir);
return FileVisitResult.CONTINUE;
}
});
}
public void register(Path dir) throws IOException {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
keys.put(key, dir);
}
public myTuple processEvents() {
WatchKey key;
//while (true) {
try {
key = watcher.take();
} catch (InterruptedException e) {
return new myTuple("INTERRUPTED", null);
}
Path dir = keys.get(key); //get next subdirectory path
if (dir == null)
return new myTuple("NULL DIRECTORY", null);
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
return new myTuple(event.kind().name(), child);
}
return null;
//}
}
@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>)event;
}
}
我的客户:
import java.nio.file.attribute.*;
import java.nio.file.*;
import java.util.concurrent.TimeUnit;
public class newClient {
public static void main(String[] args) throws IOException {
Path folder = Paths.get(System.getProperty("user.dir"));
WatchDir watcher = new WatchDir(folder, true);
myTuple thisTuple;
while (true) {
thisTuple = watcher.processEvents();
String event = thisTuple.getEvent();
Path path = thisTuple.getPath();
System.out.println(event+": "+path.toString());
}
}
}
答案 0 :(得分:0)
您没有重置密钥。再次阅读docs:
一旦处理了事件,消费者就会调用密钥 重置方法,重置密钥,允许密钥和信号 与其他事件重新排队。
可能在这里
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
return new myTuple(event.kind().name(), child);
}
key.reset();
return null;