두 개의 폴더와 하위 디렉토리를 클라이언트와 서버간에 동기화하려고합니다. 나는 아래에 게시 한 this class의 수정 된 버전을 가지고 있습니다. 클라이언트 클래스에서 WatchDir 객체를 만들고 무한 루프에서 processEvents() 메서드를 호출합니다. 이 메서드는 이벤트가 등록되어 있으면 myTuple 객체 (이벤트 유형 및 경로 객체가 포함 된 구조체)를 반환하고 그렇지 않으면 null을 반환합니다. 문제는 이것이 단지 첫 번째 이벤트가 디렉토리에서 발생하는 것처럼 보이는 것입니다 (즉, 감시 된 폴더에 파일을 추가하는 경우 WatchDir object.processEvents()는 ENTRY_CREATE 이벤트가있는 하나의 튜플을 반환하고 다른 튜플을 반환하지 않습니다) 이후에 발생하는 다른 파일 추가/삭제/수정). 나는 processEvent가 계속 호출되기를 원한다. (따라서 무한한 동안) 어떤 이벤트가 발생할 때마다 Tuple을 리턴한다. 어떤 도움을 주셔서 감사합니다! java WatchEvents를 계속 읽음
내 수정 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());
}
}
}
나는 for 루프 내에서 반환 방지하기 위해 코드를 조금 재 작업 했어하지만 다시 내가 실종됐다 정확히이었다. 감사 – WongWray