读取config 工具类
程序员文章站
2022-04-09 17:29:20
...
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* 负责提取配置文件信息,并监测配置文件的改动
*
* @author lvlj
* @datetime 2008-6-4 上午11:50:41
*/
public class ConfigUtil {
public final static String CONFIG_FILE = "/config.properties";
private static long lastModified = 0L;
private static File configFile = null;
private static Logger log = Logger.getLogger(ConfigUtil.class);
private static Properties props = new Properties();
static {
loadProperty();
}
/**
* 从配置文件中读取所有的属性
*/
private static void loadProperty() {
try {
System.out.println(ConfigUtil.class.getResource(CONFIG_FILE).getPath());
String path = ConfigUtil.class.getResource(CONFIG_FILE).getFile();
if (System.getProperty("os.name").startsWith("Windows")) {
path = path.substring(1);
path = path.replaceAll("%20", " ");
}
File f = new File(path);
lastModified = f.lastModified();
configFile = f;
log.info("load config from: " + f.getAbsolutePath());
props.load(new FileInputStream(f));
//(new ReloadThread()).start();
} catch (Exception e) {
log.error("load config falied!", e);
System.exit(-1);
}
}
/**
* 检测config文件是否被改动,改动后立即更新
*/
private static void checkUpdate() {
if (configFile != null) {
long m = configFile.lastModified();
if (m != lastModified) {
lastModified = m;
try {
Properties prop = new Properties();
prop.load(new FileInputStream(configFile));
props = prop;
log.info("reload config file:" + configFile.getAbsolutePath());
} catch (Exception e) {
log.error("failed to reload config file: " + configFile.getAbsolutePath(), e);
}
}
}
}
/**
* 根据属性名获得对应值,如果得不到值返回defaultValue
*/
public static String getConfig(String name, String defaultValue) {
checkUpdate();
String ret = props.getProperty(name, defaultValue);
if (ret == null) {
return defaultValue;
} else {
return ret.trim();
}
}
public static String getConfig(String name) {
return getConfig(name, null);
}
/**
* 检测config文件是否被改动的线程,每5秒检测一次
*/
static class ReloadThread extends Thread {
public void run() {
log.info("update checking for config file: " + configFile.getAbsolutePath());
while (true) {
System.out.println("dfghjkllkjhgfdfghj");
if (configFile != null) {
long m = configFile.lastModified();
if (m != lastModified) {
lastModified = m;
try {
Properties prop = new Properties();
prop.load(new FileInputStream(configFile));
props = prop;
log.info("config file changed, reload: " + configFile.getAbsolutePath());
} catch (Exception e) {
log.error("failed to reload config file: " + configFile.getAbsolutePath(), e);
}
}
try {
Thread.sleep(5000);
} catch (Exception e) {
log.error("", e);
}
} else
break;
}
}
}
}
上一篇: 第十二章:IO流
下一篇: js获取Url,域名,端口号等