Java WatchService文件夹监控

1 Java监控指定目录

问题:Java如何如何监控指定目录文件创建及其修改,删除等操作尼?
Java 利用 WatchService 类,利用操作系统本身的文件监控器对目录和文件进行监控,当被监控对象发生变化时,会有信号通知,从而可以高效的发现变化。
springboot2.0开发环境下核心代码实现

  1. WatchService 服务类初始化操作
package com.ccbobe.websocket.watch;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.WatchService;
/**
 * @Author:ccbobe
 * 文件目录监控
 */
@Slf4j
@Service
public class FileMonitor implements InitializingBean, DisposableBean {

    private WatchService watchService;

    @Override
    public void destroy() throws Exception {
        log.info("文件监控器销毁.....");
        if (watchService!=null){
            watchService.close();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.init();
    }

    public void init() throws IOException {
        log.info("文件监控器初始化.......");
        this.watchService = FileSystems.getDefault().newWatchService();
    }

    public WatchService getWatchService() {
        return watchService;
    }

    public void setWatchService(WatchService watchService) {
        this.watchService = watchService;
    }
}

  1. 监控核心逻辑代码如下
package com.ccbobe.websocket.watch;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.nio.file.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ccbobe
 */
@Slf4j
@Component
public class CommandRunner implements CommandLineRunner {

    @Autowired
    private FileMonitor fileMonitor;

    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    @Override
    public void run(String... args) throws Exception {
        log.info("开始监控指定文件");
        //指定监控文件目录
        Path path = Paths.get("C:\\data\\downland\\");
        //获取监控服务类
        final WatchService watchService = fileMonitor.getWatchService();
        //监听创建和删除事件
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE
                ,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);

        executorService.submit(()->{
            while (true) {
                WatchKey watchKey = null;
                try {
                    //阻塞操作
                    watchKey = watchService.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (WatchEvent event : watchKey.pollEvents()) {
                    WatchEvent.Kind eventKind = event.kind();
                    if (eventKind == StandardWatchEventKinds.OVERFLOW) {
                        continue;
                    }
                    String fileName = event.context().toString();
                    log.info("当前文件变化{}==>{}",fileName,event.kind().name());
                    //相关业务操作
                }
                //重置监控器进行下一个文件监控
                boolean isKeyValid = watchKey.reset();
                if (!isKeyValid) {
                    break;
                }
            }
        });
    }
}

总结:
1 WatchService 编程监控文件变动创建只能监控最新创建、最新修改,最新删除等文件操作,历史文件记录只能监控修改,删除操作;
2 对于指定目录及其子目录下监控有效,目录太深监控无效;

完整代码仓库地址

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值