import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 读取独立配置的properties工具
*/
public class ConfigReader {
private ConfigReader() {
}
private final static String BASE_CONFIG = "base_config";
private static Map pmap = new HashMap();
private static String[] CONFIG_FILES = { "config.properties" };// 配置文件
static {
try {
// 加载多个配置文件
Properties prop = loadProperties(CONFIG_FILES);
pmap.put(BASE_CONFIG, prop);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** * 获取服务参数配置 * @param key * @return */
public final static String getConfig(String key) {
return ((Properties) pmap.get(BASE_CONFIG)).getProperty(key);
}
/**
* 载入属性文件
* @param file 文件基于类路径的相对路径名
* @return Properties 根据属性文件生成的Properties对象
* @throws IOException
*/
private final static Properties loadProperties(String... file)
throws IOException {
Properties result = new Properties();
for (int i = 0; file != null && i < file.length; i++) {
InputStream in = getResourceAsStream(file[i]);
if (in != null) {
try {
result.load(in);
} finally {
in.close();
}
} else {
throw new IOException("载入属性文件 " + file + " 失败!");
}
}
return result;
}
/** 根据给定名字查找资源,返回其输入流
* @param uri 资源名
* @return 输入流
*/
private final static InputStream getResourceAsStream(String uri) {
return ConfigReader.class.getClassLoader().getResourceAsStream(uri);
}
}