借助JDK7中WatchService实现文件变更监听

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.IOException;
import java.nio.file.*;
import java.util.Objects;
import java.util.Properties;


/**
 * @author Created by niugang on 2019/10/16/19:41
 */
@SuppressWarnings("InfiniteLoopStatement")
public class WatchServiceDemo {
    private static String fileName="mail.properties";
    private static FileSystemResource classPathResource = null;
    private static WatchService watchService = null;

    public static Properties properties;


    static {

        String filePath = "D:/home/conf/mail.properties";
        //从文件系统加载文件
        classPathResource = new FileSystemResource(filePath);
        //监听filenam所在的目录下的文件修改、删除事件
        try {
            watchService = FileSystems.getDefault().newWatchService();
            Paths.get(classPathResource.getFile().getParent()).register(watchService,
                    StandardWatchEventKinds.ENTRY_MODIFY,
                    StandardWatchEventKinds.ENTRY_DELETE
            );
            properties = PropertiesLoaderUtils.loadProperties(classPathResource);
        } catch (IOException e) {
            e.printStackTrace();
        }


        Thread watchThread = new Thread() {
            @Override
            public void run() {

                while (true) {
                    WatchKey watchKey = null;
                    try {
                        watchKey = watchService.take();
                        for (WatchEvent<?> event : watchKey.pollEvents()) {
                            if (Objects.equals(event.context().toString(), fileName)) {
                                properties = PropertiesLoaderUtils.loadProperties(classPathResource);
                                break;
                            }
                        }
                        watchKey.reset();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (watchKey != null) {
                            watchKey.reset();
                        }
                    }


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

       //JVM停止时 关闭
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                try {
                    watchService.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

//
//    public static void main(String[] args) throws InterruptedException {
//        //验证  启动main方法   修改mail.properties文件 看控制台输出内容的变化
//        while (true){
//            System.out.println(properties);
//            Thread.sleep(5000);
//        }
//
//
//
//    }

}

微信公众号
JAVA程序猿成长之路

posted @ 2020-01-13 14:11  盲目的拾荒者  阅读(324)  评论(0编辑  收藏  举报