本篇文章主要介绍了java利用watchservice监听文件变化示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
在实现配置中心的多种方案中,有基于jdk7+的watchservice方法,其在单机应用中还是挺有实践的意义的。
代码如下:
package com.longge.mytest;
import java.io.ioexception;
import java.nio.file.filesystems;
import java.nio.file.path;
import java.nio.file.paths;
import java.nio.file.standardwatcheventkinds;
import java.nio.file.watchevent;
import java.nio.file.watchkey;
import java.nio.file.watchservice;
import java.util.list;
/**
* 测试jdk的watchservice监听文件变化
* @author yangzhilong
*
*/
public class testwatchservice {
public static void main(string[] args) throws ioexception {
// 需要监听的文件目录(只能监听目录)
string path = "d:/test";
watchservice watchservice = filesystems.getdefault().newwatchservice();
path p = paths.get(path);
p.register(watchservice, standardwatcheventkinds.entry_modify,
standardwatcheventkinds.entry_delete,
standardwatcheventkinds.entry_create);
thread thread = new thread(() -> {
try {
while(true){
watchkey watchkey = watchservice.take();
list<watchevent<?>> watchevents = watchkey.pollevents();
for(watchevent<?> event : watchevents){
//todo 根据事件类型采取不同的操作。。。。。。。
system.out.println("["+path+"/"+event.context()+"]文件发生了["+event.kind()+"]事件");
}
watchkey.reset();
}
} catch (interruptedexception e) {
e.printstacktrace();
}
});
thread.setdaemon(false);
thread.start();
// 增加jvm关闭的钩子来关闭监听
runtime.getruntime().addshutdownhook(new thread(() -> {
try {
watchservice.close();
} catch (exception e) {
}
}));
}
}
运行示例结果类似如下:
[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]事件
以上就是java如何使用watchservice监听文件变化的代码案例分享的详细内容。