使用WatchService

时间:2017-02-28 19:55:50

标签: java events watchservice

对于我目前的副项目,我需要利用WatchService来跟踪给定目录中的事件。我的代码主要基于Oracles WatchService tutorial example

但我需要将其限制为仅文件夹事件(例如ENTRY_CREATE C:\ temp \ folder_a)。

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

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

  • fileCache
  • 中的文件的事件上下文
  • 是事件上下文的新文件( - > Files.isRegularFile)

因此,应丢弃新的File事件或来自缓存中已有文件的事件。

但打印出事件会产生

  

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

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: %s\n", dir);
        } else {
            if (!dir.equals(prev)) {
                System.out.format("update: %s -> %s\n", 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: %s\n", 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

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);
    }
}

1 个答案:

答案 0 :(得分:0)

您正在收听文件系统中的所有可能事件,因此无需提出更多要求。如果操作系统没有呈现更多事件并且更详细,那么Java无法做任何事情。一些复杂的文件系统操作不是由一个事件表示,而是由一系列基本事件表示。所以你必须充分利用这些事件,并且必须解释一系列事件实际意味着什么。