public static void fileListener(String filePath) throws InterruptedException,IOException{
// 获取文件系统的WatchService对象
WatchService watchService = FileSystems.getDefault().newWatchService();
String parentPath = filePath.substring(0,filePath.lastIndexOf(File.separator));
Paths.get(parentPath).register(watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.ENTRY_DELETE);
while(true)
{
// 获取下一个文件改动事件
WatchKey key = watchService.take();
for (WatchEvent<?> event : key.pollEvents())
{
System.out.println(event.context() +" --> " + event.kind());
File file = new File(filePath);
if(!file.exists()){
log.error(filePath+"cnr配置文件不存在");
break;
}
String ms= IOUtils.readFile(filePath);
paramSetService.addParamSet(ms);
}
// 重设WatchKey
boolean valid = key.reset();
// 如果重设失败,退出监听
if (!valid)
{
break;
}
}
}
WatchFile监听目录下文件的改动
最新推荐文章于 2025-06-26 09:11:43 发布