java7 watchservice_借助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);

// }

//

//

//

// }

}

微信公众号

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值