iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >java.nio.file.WatchService 实时监控文件变化的示例代码
  • 854
分享到

java.nio.file.WatchService 实时监控文件变化的示例代码

2024-04-02 19:04:59 854人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录1.示例代码2.其实并没有实时在平时的开发过程中,会有很多场景需要实时监听文件的变化,如下:1、通过实时监控 Mysql 的 binlog 日志实现数据同步2、修改配置文件后,希

在平时的开发过程中,会有很多场景需要实时监听文件的变化,如下:
1、通过实时监控 Mysql 的 binlog 日志实现数据同步
2、修改配置文件后,希望系统可以实时感知
3、应用系统将日志写入文件中,日志监控系统可以实时抓取日志,分析日志内容并进行报警
4、类似 ide 工具,可以实时感知管理的工程下的文件变更

在 Java 语言中,从 jdk7 开始,新增了java.NIO.file.WatchService类,用来实时监控文件的变化。

1.示例代码

FileWatchedService 类:

package org.learn.file;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;


public class FileWatchedService {
    private WatchService watchService;

    private FileWatchedListener listener;

    
    public FileWatchedService(Path path, FileWatchedListener listener) throws IOException {
        watchService = FileSystems.getDefault().newWatchService();
        path.reGISter(watchService,
                /// 监听文件创建事件
                StandardWatchEventKinds.ENTRY_CREATE,
                /// 监听文件删除事件
                StandardWatchEventKinds.ENTRY_DELETE,
                /// 监听文件修改事件
                StandardWatchEventKinds.ENTRY_MODIFY);
//
//            path.register(watchService,
//                    new WatchEvent.Kind[]{
//                            StandardWatchEventKinds.ENTRY_MODIFY,
//                            StandardWatchEventKinds.ENTRY_CREATE,
//                            StandardWatchEventKinds.ENTRY_DELETE
//                    },
//                    SensitivityWatchEventModifier.HIGH);

        this.listener = listener;
    }

    private void watch() throws InterruptedException {
        while (true) {
            WatchKey watchKey = watchService.take();
            List<WatchEvent<?>> watchEventList = watchKey.pollEvents();
            for (WatchEvent<?> watchEvent : watchEventList) {
                WatchEvent.Kind kind = watchEvent.kind();

                WatchEvent<Path> curEvent = (WatchEvent<Path>) watchEvent;
                if (kind == StandardWatchEventKinds.OVERFLOW) {
                    listener.onOverflowed(curEvent);
                    continue;
                } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                    listener.onCreated(curEvent);
                    continue;
                } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                    listener.onModified(curEvent);
                    continue;
                } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                    listener.onDeleted(curEvent);
                    continue;
                }
            }

            
            if (!watchKey.reset()) {
                break;
            }

        }
    }

    public static void main(String[] args) {
        try {
            Path path = Paths.get("/Users/zhibo/logs/");
            FileWatchedService fileWatchedService = new FileWatchedService(path, new FileWatchedAdapter());
            fileWatchedService.watch();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

FileWatchedListener 类:

package org.learn.file;

import java.nio.file.Path;
import java.nio.file.WatchEvent;

public interface FileWatchedListener {
    void onCreated(WatchEvent<Path> watchEvent);

    void onDeleted(WatchEvent<Path> watchEvent);

    void onModified(WatchEvent<Path> watchEvent);

    void onOverflowed(WatchEvent<Path> watchEvent);
}

FileWatchedAdapter 类:

package org.learn.file;

import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.text.DateFORMat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class FileWatchedAdapter implements FileWatchedListener {

    @Override
    public void onCreated(WatchEvent<Path> watchEvent) {
        Path fileName = watchEvent.context();
        System.out.println(String.format("文件【%s】被创建,时间:%s", fileName, now()));
    }

    @Override
    public void onDeleted(WatchEvent<Path> watchEvent) {
        Path fileName = watchEvent.context();
        System.out.println(String.format("文件【%s】被删除,时间:%s", fileName, now()));
    }

    @Override
    public void onModified(WatchEvent<Path> watchEvent) {
        Path fileName = watchEvent.context();
        System.out.println(String.format("文件【%s】被修改,时间:%s", fileName, now()));
    }

    @Override
    public void onOverflowed(WatchEvent<Path> watchEvent) {
        Path fileName = watchEvent.context();
        System.out.println(String.format("文件【%s】被丢弃,时间:%s", fileName, now()));
    }

    private String now(){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        return dateFormat.format(Calendar.getInstance().getTime());
    }
}

执行以上代码,启动监控任务,然后我在/Users/zhibo/logs/目录中创建、修改、删除文件,命令如下:

在这里插入图片描述

应用程序感知到文件变化,打印日志如下:

在这里插入图片描述

2.其实并没有实时

大家可以看到,监控任务基本上是以 10 秒为单位进行日志打印的,也就是说修改一个文件,WatchService 10秒之后才能感知到文件的变化,没有想象中的那么实时。根据以上的经验,推测可能是 WatchService 做了定时的操作,时间间隔为 10 秒。通过翻阅源代码发现,在 PollingWatchService 中确实存在一个固定时间间隔的调度器,如下图:

在这里插入图片描述

该调度器的时间间隔有 SensitivityWatchEventModifier 进行控制,该类提供了 3 个级别的时间间隔,分别为2秒、10秒、30秒,默认值为 10秒。SensitivityWatchEventModifier 源码如下:

package com.sun.nio.file;

import java.nio.file.WatchEvent.Modifier;

public enum SensitivityWatchEventModifier implements Modifier {
    HIGH(2),
    MEDIUM(10),
    LOW(30);

    private final int sensitivity;

    public int sensitivityValueInSeconds() {
        return this.sensitivity;
    }

    private SensitivityWatchEventModifier(int var3) {
        this.sensitivity = var3;
    }
}

通过改变时间间隔来进行验证,将

        path.register(watchService,
                /// 监听文件创建事件
                StandardWatchEventKinds.ENTRY_CREATE,
                /// 监听文件删除事件
                StandardWatchEventKinds.ENTRY_DELETE,
                /// 监听文件修改事件
                StandardWatchEventKinds.ENTRY_MODIFY);

修改为:

    path.register(watchService,
                    new WatchEvent.Kind[]{
                            StandardWatchEventKinds.ENTRY_MODIFY,
                            StandardWatchEventKinds.ENTRY_CREATE,
                            StandardWatchEventKinds.ENTRY_DELETE
                    },
                    SensitivityWatchEventModifier.HIGH);

查看日志,发现正如我们的推断,WatchService 正以每 2 秒的时间间隔感知文件变化。
在 stackoverflow 中也有人提出了该问题,问题:Is Java 7 WatchService Slow for Anyone Else,我的 Mac 系统中确实存在该问题,由于手头没有 windowslinux 系统,因此无法进行这两个系统的验证。

到此这篇关于java.nio.file.WatchService 实时监控文件变化的文章就介绍到这了,更多相关java.nio.file.WatchService 监控文件变化内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: java.nio.file.WatchService 实时监控文件变化的示例代码

本文链接: https://www.lsjlt.com/news/150125.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作