package com.hpli.demo;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import com.huawei.hispace.test.common.Constants;
/**
* 配置文件帮助类
*
* @author hpli/025415
* @version [版本号, 2012-3-22]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class ConfigHelper
{
private static Map<String, Properties> configMap;
/**
* 配置文件的fileName
*/
private static String[] fileNames = new String[1];
static
{
fileNames[0] = "config";
init();
}
private ConfigHelper()
{
}
/**
* 初试化方法
*/
public static void init()
{
// 得到工程绝对路径D:\hpli\Workspace\HispaceTest\WebRoot\WEB-INF\classes
// String path = this.getClass().getResource("/").getPath();
configMap = new HashMap<String, Properties>(0);
Properties properties = null;
InputStream inStream = null;
try
{
for (int i = 0; i < fileNames.length; i++)
{
properties = new Properties();
inStream = ClassLoader.getSystemResourceAsStream(fileNames[i]
+ ".properties");
properties.load(inStream);
configMap.put(fileNames[i], properties);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
inStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* 获取配置文件
* @param keyProperties 配置文件key
* @return 返回配置文件Properties对象
*
* @return Properties 返回配置文件Properties对象
* @exception throws [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public static Properties getConfig(String keyProperties)
{
return configMap.get(keyProperties);
}
/**
* 读取默认文件
*/
public static Properties getConfig()
{
return getConfig(Constants.DEFAULT_CONFIG);
}
/**
* 获取默认配置文件中的属性值 方法表述
* @param key 键值
* @return 配置文件属性值 String
*/
public static String getCfg(String key)
{
Properties config = getConfig();
if (config == null)
{
return "";
}
if (config.containsKey(key))
{
return config.getProperty(key);
}
return "";
}
/**
* 读取指定配置文件数据
* @param keyProperties 指定配置文件名
* @param key 获取的key值
* @return key对应的value
*
* @return String key对应的value
* @exception throws [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public static String getCfg(String keyProperties, String key)
{
Properties config = getConfig(keyProperties);
if (config == null)
{
return "";
}
if (config.containsKey(key))
{
return config.getProperty(key);
}
return "";
}
/**
* 重新讀取
*/
public static void reload()
{
configMap = new HashMap<String, Properties>(0);
init();
}
public static void main(String[] args)
{
System.out.println(ConfigHelper.getConfig().get("configName"));
}
}