监听本地文件的变化

package com.taobao.jnpiter.eros.common.util;


import java.io.File;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class WatchFile {

    private static WatchService watchService;
    private static String filePath;

    public void watch() {

        //目录全路径
        filePath = "/Users/zhenyuan.he/Desktop/coding/new/eros";

        try {
            // 获取文件系统的WatchService对象
            watchService = FileSystems.getDefault().newWatchService();
            File file = new File(filePath);
            List<String> fileNames = new ArrayList<>();
            findContainsFileDir(file, ".class", fileNames);
            for (String fileName : fileNames) {
                System.err.println("fileName=" + fileName);
                // 监听filePath目录下文件是否修改或增加;register()方法后面监听事件种类还可以增加、删除。
                Paths.get(fileName).register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_MODIFY); //监听修改、添加
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        // 设置后台线程
        Thread watchThread = new Thread(new Runnable() {

            private Set<String> fileNameSet = new HashSet<>(); //Set去重,当添加文件的时候,修改时间也会被监听执行

            @Override
            public void run() {
                while (true) {
                    try {
                        // 获取下一个文件改动事件
                        WatchKey key = watchService.take();
                        for (WatchEvent<?> event : key.pollEvents()) {
                            fileNameSet.add(event.context() + "");
                        }
                        for (String name : fileNameSet) {
                            System.out.println("文件:" + filePath + "/" + name);
                        }
                        // 重设WatchKey
                        boolean valid = key.reset();
                        fileNameSet.clear();

                        // 如果重设失败,退出监听
                        if (!valid) {
                            break;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        // 设置为后台守护线程
        watchThread.setDaemon(true);
        watchThread.start();

    }

    /**
     * 读取目录下的所有文件
     *
     * @param dir       目录
     * @param fileNames 保存文件名的集合
     * @return
     */
    public static void findContainsFileDir(File dir, String fileType, List<String> fileNames) {

        // 判断是否存在目录
        if (dir == null || !dir.exists() || !dir.isDirectory()) {
            return;
        }
        // 读取目录下的所有目录文件信息
        String[] files = dir.list();

        for (int i = 0; i < files.length; i++) {
            File file = new File(dir, files[i]);
            // 如果文件
            if (file.isFile() && file.getName().endsWith(fileType)) {
                if (!fileNames.contains(dir.getPath())) {
                    fileNames.add(dir.getPath());
                }
            } else {
                findContainsFileDir(file, fileType, fileNames);
            }
        }
    }

    /**
     * 读取目录下的所有文件
     *
     * @param dir       目录
     * @param fileNames 保存文件名的集合
     * @return
     */
    public static void findFileList(File dir, List<String> fileNames) {

        // 判断是否存在目录
        if (dir == null || !dir.exists() || !dir.isDirectory()) {
            return;
        }
        // 读取目录下的所有目录文件信息
        String[] files = dir.list();
        for (int i = 0; i < files.length; i++) {
            File file = new File(dir, files[i]);
            // 如果文件
            if (file.isFile()) {
                fileNames.add(dir + "\\" + file.getName());
            } else {
                findFileList(file, fileNames);
            }
        }
    }

    /**
     * 模拟测试
     */
    public static void main(String[] args) throws Exception {

        // 开启监听程序,如有改动,则更新对象
        WatchFile w = new WatchFile();
        w.watch();

        // 假装做一些事情,延迟。
        Thread.sleep(8000000000000L);

    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值