0

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

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 接收到该事件。

4

0 回答 0