使用WatchService在Java中停止文件修改时如何在文件上触发事件?

时间:2013-05-09 06:51:19

标签: java polling watchservice

我一直在使用WatchService api来实现这一点。我想检查文件是否保持10秒不变,如果是,则处理该文件。我已经开发了一个代码,用于检查文件是否已被修改,但我无法确定上次修改时间。请编辑我的代码或建议任何其他答案。

public class Poller {
public static void main(String[] args) throws URISyntaxException,
        IOException, InterruptedException {
    Date oldDate;
    Path tmpPath = Paths.get("E:/Demo/DEC");
    WatchService watchService = FileSystems.getDefault().newWatchService();

    // Watching the /tmp/nio/ directory
    // for MODIFY and DELETE operations
    tmpPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
            StandardWatchEventKinds.ENTRY_DELETE);

    /*
     * Keep polling for events on the watched directory,
     */
    for (;;) {
        WatchKey key = watchService.take();

        // Poll all the events queued for the key
        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind kind = event.kind();
            switch (kind.name()) {
            case "ENTRY_MODIFY":
                Path filename = (Path) event.context();
                System.out.println("Modified: " + event.context());
                break;
            case "ENTRY_DELETE":
                System.out.println("Delete: " + event.context());
                break;
            }
        }
        // reset is invoked to put the key back to ready state
        boolean valid = key.reset();

        // If the key is invalid, just exit.
        if (!valid) {
            break;
        }
    }

}
}

假设我在指定文件夹中有一个名为input.csv的文件,并且在代码运行时,我修改了input.csv,然后WatchService API接收到该事件。

0 个答案:

没有答案