說明: 主要應用方法: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); } }