Java 读取配置文件方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值