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);
}
}