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

说明: 主要应用方法:java

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

 

调用方法:spa

调用方法, 在调用类中 // 静态初始化读入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", "###");
.net

 

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

 

 

package com.todod.common.util;资源

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

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

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

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

相关文章
相关标签/搜索