使用WatchService忽略文件事件(创建,修改,删除)



对于我当前的侧面项目,我需要使用手表服务来跟踪给定目录中的事件。我的代码仍主要基于Oracles WatchService教程示例

我需要将其限于文件夹仅事件(例如Entry_Create c: temp folder_a)。

我要做的是拍摄目录内容的初始快照并将每个内容路径存储到 dircache filecache

如果注册了新事件,则应检查:

  • 是事件上下文 filecache中的文件
  • 是事件上下文一个新文件( -> files.isregularfile)

因此,两个新文件事件都应被丢弃或从缓存中的文件中丢弃。

但是打印出事件会产生

entry_delete:c: temp k.txt

用于文件,但没有entry_create或entry_modify。

我在做什么错?我是不正确检查缓存还是完全不同的东西?

这是当前的代码库:

public class Main {
    public static void main(String[] args) {
        try {
            new DirectoryWatcher(Paths.get("C:\temp")).processEvents();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

DirectoryWatcher class

package service;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.HashMap;
import java.util.Map;
/**
 * Slightly modified version of Oracle
 * example file WatchDir.java
 * /
public class DirectoryWatcher {
    private final Path path;
    private final WatchService watcher;
    private final Map<WatchKey,Path> keys;
    private PathSnapshot pathSnapshot;
    private boolean trace = false;
@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
    return (WatchEvent<T>)event;
}
/**
 * Register the given directory with the WatchService
 */
private void register(Path dir) throws IOException {
    WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    if (trace) {
        Path prev = keys.get(key);
        if (prev == null) {
            System.out.format("register: %sn", dir);
        } else {
            if (!dir.equals(prev)) {
                System.out.format("update: %s -> %sn", prev, dir);
            }
        }
    }
    keys.put(key, dir);
}
public DirectoryWatcher(Path dir) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.keys = new HashMap<WatchKey,Path>();
    this.path = dir;
    this.pathSnapshot = new PathSnapshot(dir);
    register(dir);
    // enable trace after initial registration
    this.trace = true;
}
/**
 * Process all events for keys queued to the watcher
 */
void processEvents() {
    for (;;) {
        // wait for key to be signaled
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }
        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }
        for (WatchEvent<?> event: key.pollEvents()) {
            Kind<?> kind = event.kind();
            // TBD - provide example of how OVERFLOW event is handled
            if (kind == OVERFLOW) {
                continue;
            }
            // Context for directory entry event is the file name of entry
            WatchEvent<Path> ev = cast(event);
            Path name = ev.context();
            Path child = dir.resolve(name);
            this.updateDirContent();
            /*
             * currently: creating file events are neglected 
             * but deleting a file creates an event which is printed
             * TODO: disregard delete event if sent from file
             */
            boolean isFile = Files.isRegularFile(child);
            if (pathSnapshot.isInFileCache(child)|| isFile) {
                //disregard the event if file
                event = null;
            } else {
                // print out event
                System.out.format("%s: %sn", event.kind().name(), child);
            }
        }
        // reset key and remove from set if directory no longer accessible
        boolean valid = key.reset();
        if (!valid) {
            keys.remove(key);
            // all directories are inaccessible
            if (keys.isEmpty()) {
                break;
            }
        }
    }
}
private void updateDirContent() {
    this.pathSnapshot = pathSnapshot.updateSnapshot(path);
}
}

pathsnapshot class

package service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.stream.Stream;
public class PathSnapshot {
    public ArrayList<Path> dirCache = new ArrayList<Path>();
    public ArrayList<Path> fileCache = new ArrayList<Path>();
    public PathSnapshot(Path dir) {
        try {
            Stream<Path> rawDirContent = Files.walk(
                    dir, 1);
            Object[] dirContent = rawDirContent.toArray();
            rawDirContent.close();
            sortIntoCache(dirContent, dir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void sortIntoCache(Object[] dirContent, Path rootdir) {
        for (Object object : dirContent) {
            //create path from element
            Path objectPath = Paths.get(object.toString());
            //skip start path / the root directory
            if (object.equals(rootdir)) {
                continue;
            } else if (Files.isRegularFile(objectPath)) {
                fileCache.add(objectPath);
            } else if (Files.isDirectory(objectPath)) {
                dirCache.add(objectPath);
            }
        } 
    }
    public boolean isInFileCache(Path path) {
        if (fileCache.contains(path)) {
            return true;
        } else {
            return false;
        }
    }
    public boolean isInDirCache(Path path) {
        if (dirCache.contains(path)) {
            return true;
        } else {
            return false;
        }
    }
    public PathSnapshot updateSnapshot(Path dir){
        return new PathSnapshot(dir);
    }
}

您正在聆听文件系统中的所有可能事件,因此没有更多要求。如果操作系统不提出更多的事件和更详细的信息,Java将无能为力。某些复杂的文件系统操作只是一个事件而不是一系列基本事件来表示。因此,您必须从事件中充分利用,并且必须解释一系列事件的实际含义。

相关内容

  • 没有找到相关文章

最新更新