2

我有 2 个文件夹,我为每个文件夹注册了一个具有相同 WatchService 的 WatchKey...当我在一个文件夹中更改某些内容时,显然会有一个 WatchEvent。但是当我有一个事件时,我想更改另一个文件夹中的某些内容,而不需要为另一个文件夹获取另一个事件。因为那会导致无限循环:(

我这样的代码不能正常工作:

while (true) {
        try {
            key = watcher.take();
            keypath = (Path) key.watchable();
            list = key.pollEvents();
            for (WatchEvent<?> e : list) {
                if (e.kind() == OVERFLOW) {
                    System.err.println("OVERFLOW!");
                    break;
                } else {
                    file = new File(keypath.toString() + "\\" + e.context().toString());
                    System.out.println("FileChange detected: \"" + file + "\" [" + e.kind() + "]");
                    WatchKey other = getKey(getOtherFile(file));
                    other.cancel();
                    new Thread(new WatcherSync(this, file, sync)).start();
                    registerWatchKey((Path)other.watchable());
                }
            }
            if (!key.reset()) {
                System.err.println("Reset failed for WatchKey: " + keypath);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
4

0 回答 0