简体   繁体   English

当未使用Java WatchService修改文件时,如何触发事件?

[英]How to fire an event when a file is not been modified using Java WatchService?

I want to fire an event whenever a file has stopped being modified. 每当文件停止被修改时,我都想触发一个事件。 I am polling a directory and if the filename matches to "input.csv" then i want to fire an event on that file. 我正在轮询目录,如果文件名匹配“ input.csv”,那么我想在该文件上触发事件。 Time to check whether the file has been modified is 10 seconds. 检查文件是否已修改的时间为10秒。 I am getting a null pointer exception when no event occurs. 没有事件发生时,我得到一个空指针异常。 This is my sample code: 这是我的示例代码:

public class MyPoller {
public static void main(String[] args) throws URISyntaxException,
        IOException, InterruptedException {
    Path tmpPath = Paths.get("E:/MyDirectory/DEC");
    WatchService watchService = FileSystems.getDefault().newWatchService();
    // Watching the E:/MyDirectory/DEC directory
    // for MODIFY and DELETE operations
    tmpPath.register(watcput.csvService, StandardWatchEventKinds.ENTRY_MODIFY,
            StandardWatchEventKinds.ENTRY_DELETE);
    for (;;) {
        WatchKey key = watchService.poll(10000,TimeUnit.MILLISECONDS);
         List<WatchEvent<?>> events = key.pollEvents();

        // Poll all the events queued for the key
        for (WatchEvent event : events) {

            switch (event.context().toString()) {
            case "input.csv":
                System.out.println("Modified: " + event.context());
                String filename = "" + event.context();
                System.out.println(" "+filename);

                break;

                default:
                    break;
            }
        }
        boolean valid = key.reset();

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

}
}

If no event is generated, then the WatchKey may be null 如果未生成任何事件,则WatchKey可能为null

WatchKey key = watchService.poll(10000,TimeUnit.MILLISECONDS);

Try to do a null check on the key and then proceed to do pollEvents() if it's indeed not null . 尝试对键进行null检查,如果确实不为null ,则继续执行pollEvents()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM