1

我想在文件停止修改时触发一个事件。我正在轮询一个目录,如果文件名与“input.csv”匹配,那么我想在该文件上触发一个事件。检查文件是否被修改的时间为 10 秒。当没有事件发生时,我得到一个空指针异常。这是我的示例代码:

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

}
}
4

1 回答 1

2

如果没有事件产生,那么 WatchKey 可能是null

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

尝试检查密钥,如果确实不是null,则继续进行。pollEvents()null

于 2014-05-07T13:20:27.003 回答