使用JAVA的NIO监测指定文件夹下的所有文件,event.context()可以获取发生变化的文件名。
下面这段代码,创建指定配置文件(如果配置文件不存在,在classpath目录下),由于我的配置文件只有一行内容,所以读取一行就行了。
需要单独开一个线程执行下列任务,否则take方法会阻塞主线程。
static {
Path path= null;
try {
path = Paths.get( Thread.currentThread().getContextClassLoader().getResource("").toURI());
path= path.resolve("rate.properties");
if (!Files.exists(path)){
Files.write(path,BOUNDARY.toString().getBytes(),StandardOpenOption.CREATE);
}
WatchService watchService = FileSystems.getDefault().newWatchService();
WatchKey key=path.getParent().register(watchService, ENTRY_MODIFY);
while (true) {
key = watchService.take();
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind() == ENTRY_MODIFY && event.context().equals(path.getFileName())) {
List<String> lines = Files.readAllLines(path);
if (lines!=null && lines.size()>0){
BOUNDARY = Integer.parseInt(lines.get(0));
}
}
key.reset();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}