最近做的一个项目用到了很多配置文件,当一个文件改动之后,项目必须重启才可以使改动生效,所以利用空余时间写了这么个小程序,希望大神指点,也希望能给看到的朋友帮助。废话不多说,开始。
程序的思路:使用多线程每个一定时间检查配置文件的最后修改日期,如果和程序中保存的不一致,那就重新读取这些资源。
package com.utils.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
public class FileReload {
private Properties properties;
private String filePath;
public FileReload(String filePath) {
super();
this.filePath = filePath;
}
public String getAge() {
return properties.getProperty("age");
}
public String getName() {
return properties.getProperty("name");
}
public void startCheck(String fileName){
File file = new File(fileName);
startCheck(file);
}
//初始化代码,将数据读取到内存中,这里面是我的实现,可以根据不同的需求更改实现
public void init(){
if(properties == null)
properties = new Properties();
InputStream in = null;
try {
in = new FileInputStream(new File(this.filePath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
if(in == null)
in = this.getClass().getResourceAsStream(this.filePath);
if(in == null)
in = this.getClass().getClassLoader().getResourceAsStream(this.filePath);
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
//开始监控
startCheck(this.filePath);
}
//开始监控
public void startCheck(final File file){
Runnable checkThread = new Runnable() {
private long lastModified;
@Override
public void run() {
long lastModified = file.lastModified();
if(this.lastModified != lastModified){
this.lastModified = lastModified;
init();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(checkThread);
thread.start();
}
public static void main(String[] args) {
String filePath = "d://test.properties";
final FileReload reload = new FileReload(filePath);
reload.init();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(reload.getAge() + "-----" + reload.getName());
}
}, new Date(), 1000);
}
}