Java7 文件变动监听

Java About 1,794 words

使用场景

应用配置热更新。

代码

可用于监听单个文件变更。

public static void main(String[] args) {
    try {
        String filePath = System.getProperty("user.home");
        WatchService watchService = FileSystems.getDefault().newWatchService();
        Path path = Paths.get(filePath);
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW);
        System.out.println("开始监听文件夹#" + filePath);
        WatchKey key;
        while ((key = watchService.take()) != null) {
            List<WatchEvent<?>> watchEvents = key.pollEvents();
            for (WatchEvent<?> watchEvent : watchEvents) {
                WatchEvent.Kind<?> kind = watchEvent.kind();
                if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                    System.out.println("新建#" + watchEvent.context() + ", 次数#" + watchEvent.count());
                } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                    System.out.println("删除#" + watchEvent.context() + ", 次数#" + watchEvent.count());
                } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                    System.out.println("修改#" + watchEvent.context() + ", 次数#" + watchEvent.count());
                } else if (kind == StandardWatchEventKinds.OVERFLOW) {
                    System.out.println("overflow#" + watchEvent.context() + ", 次数#" + watchEvent.count());
                }
            }
            key.reset();
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("获取监听器失败");
    }
}

注意

  • WatchService监听的是文件夹,而不是文件。
  • 修改事件会连续触发两次,需去重。
  • 只监听一级目录,二级目录事件不监听。

参考

https://docs.oracle.com/javase/tutorial/essential/io/notification.html

Views: 2,179 · Posted: 2020-09-27

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh