package com.hpli.demo;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 配置文件帮助类
*
* @author hpli/025415
* @version [版本号, 2012-3-22]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class ConfigHelper
{
// 定义默认读取文件对象
private static String DEFAULT_CONFIG = "config.properties";
// 定义properties
private static Properties properties = null;
static
{
load();
}
private ConfigHelper()
{
}
/**
* 读取对应配置文件业务
*/
public static void load()
{
// 得到工程绝对路径D:\hpli\Workspace\HispaceTest\WebRoot\WEB-INF\classes
// String path = this.getClass().getResource("/").getPath();
// 定义字节流对象
InputStream inStream = null;
try
{
// 实列化对象
properties = new Properties();
// 读取指定文件
inStream = ClassLoader.getSystemResourceAsStream(DEFAULT_CONFIG);
// 读取内容
properties.load(inStream);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
inStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* 获取默认配置文件中的属性值 方法表述
*
* @param key键值
* @return 配置文件属性值 String
*/
public static String getConfigInfo(String key)
{
// 临时value值变量
String configInfo = "";
// 如果properties对象不为空且包含对应key值时,获取返回对应value值
if (properties != null && properties.containsKey(key))
{
configInfo = properties.getProperty(key);
}
return configInfo;
}
/**
* 读取指定配置文件数据
*
* @param keyProperties 指定配置文件名
* @param key 获取的key值
* @return key对应的value
*/
public static String getConfigInfo(String keyProperties, String key)
{
// 临时value值变量
String configInfo = "";
// keyProperties不为空,读取指定配置文件信息
if (null != keyProperties && !"".equals(keyProperties))
{
DEFAULT_CONFIG = keyProperties;
load();
}
// 如果properties对象不为空且包含对应key值时,获取返回对应value值
if (properties != null && properties.containsKey(key))
{
configInfo = properties.getProperty(key);
}
return configInfo;
}
/**
* 重新讀取
*/
public static void reload()
{
load();
}
/**
* 测试
*
* @param args
*/
public static void main(String[] args)
{
System.out.println("--- key-value01:" + ConfigHelper.getConfigInfo("isDebug"));
System.out.println("--- key-value02:" + ConfigHelper.getConfigInfo("congfig02.properties", "isDebug"));
}
}