您的位置:首页 > 运维架构

读取项目下 property 的资源文件工具类

2017-03-27 00:00 246 查看
说明: 主要应用方法:

ClassLoader.getResourceAsStream()查找资源,是当前类编译为class文件后所在文件夹路径中查找,举例说明

调用方法:

调用方法, 在调用类中 // 静态初始化读入todod.properties中的设置
static {
init("todod.properties");
}
/**
* 从todod.properties中读取 对象分割符
* constant.object_split_char的值,如果配置文件不存在或配置文件中不存在该值时,默认取值###
*/
public final static String DEFAULT_OBJECT_SPLIT_CHAR = getProperty(
"constant.object_split_char", "###");

在 constant.java , 在常量类中访问property属性的好处, 只修改property即可修改常量值, 在使用类中调用比直接调用property方便很多,值得推荐

package com.todod.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* 可用Properties文件配置的Constants基类.
* 本类既保持了Constants的static和final(静态与不可修改)特性,又拥有了可用Properties文件配置的特征,
* 主要是应用了Java语言中静态初始化代码的特性.
*
* @see com.tenace.framework.Constants
*/
public class ConfigurableConstants {

protected static Logger logger = LoggerFactory
.getLogger(ConfigurableConstants.class);

protected static Properties p = new Properties();

/**
* 静态读入属性文件到Properties p变量中
*
* @param propertyFileName
*/
protected static void init(String propertyFileName) {
InputStream in = null;
try {
in = ConfigurableConstants.class.getClassLoader()
.getResourceAsStream(propertyFileName);
if (in != null)
p.load(in);
} catch (IOException e) {
logger.error("load " + propertyFileName + " into Constants error!");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
logger.error("close " + propertyFileName + " error!");
}
}
}
}

/**
* 封装了Properties类的getProperty函数,使p变量对子类透明.
*
* @param key
* property key.
* @param defaultValue
* 当使用property key在properties中取不到值时的默认值.
*/
protected static String getProperty(String key, String defaultValue) {
return p.getProperty(key, defaultValue);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  resource property与