Java利用WatchService监听文件变化示例
在实现配置中心的多种方案中,有基于JDK7+的WatchService方法,其在单机应用中还是挺有实践的意义的。
代码如下:
packagecom.longge.mytest;
importjava.io.IOException;
importjava.nio.file.FileSystems;
importjava.nio.file.Path;
importjava.nio.file.Paths;
importjava.nio.file.StandardWatchEventKinds;
importjava.nio.file.WatchEvent;
importjava.nio.file.WatchKey;
importjava.nio.file.WatchService;
importjava.util.List;
/**
*测试JDK的WatchService监听文件变化
*@authoryangzhilong
*
*/
publicclassTestWatchService{
publicstaticvoidmain(String[]args)throwsIOException{
//需要监听的文件目录(只能监听目录)
Stringpath="d:/test";
WatchServicewatchService=FileSystems.getDefault().newWatchService();
Pathp=Paths.get(path);
p.register(watchService,StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_CREATE);
Threadthread=newThread(()->{
try{
while(true){
WatchKeywatchKey=watchService.take();
List>watchEvents=watchKey.pollEvents();
for(WatchEvent>event:watchEvents){
//TODO根据事件类型采取不同的操作。。。。。。。
System.out.println("["+path+"/"+event.context()+"]文件发生了["+event.kind()+"]事件");
}
watchKey.reset();
}
}catch(InterruptedExceptione){
e.printStackTrace();
}
});
thread.setDaemon(false);
thread.start();
//增加jvm关闭的钩子来关闭监听
Runtime.getRuntime().addShutdownHook(newThread(()->{
try{
watchService.close();
}catch(Exceptione){
}
}));
}
}
运行示例结果类似如下:
[d:/test/1.txt]文件发生了[ENTRY_MODIFY]事件
[d:/test/1.txt]文件发生了[ENTRY_DELETE]事件
[d:/test/新建文本文档.txt]文件发生了[ENTRY_CREATE]事件
[d:/test/新建文本文档.txt]文件发生了[ENTRY_DELETE]事件
[d:/test/222.txt]文件发生了[ENTRY_CREATE]事件
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。