import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 配置文件读取工具
*/
public class ConfigurableConstants
{
protected static final String PROPERTIES_PATH = "config.properties";
protected static Log logger = LogFactory.getLog(ConfigurableConstants.class);
protected static Properties p = new Properties();
static
{
init(PROPERTIES_PATH);
}
/**
* 静态读入属性文件到Properties p变量中
*/
protected static void init(String propertyFileName)
{
InputStream in = null;
try
{
// class.getClassLoader()获得该class文件加载的web应用的目录,如WEB-INF/classes/就是根目录
// getResourceAsStream(relativeFilePath):定位该文件且获得它的输出流
in = ConfigurableConstants.class.getClassLoader().getResourceAsStream(propertyFileName);
BufferedReader bf = null;
if (in != null)
// load输出流到Properties对象中
// 因为字节流是无法读取中文的,所以采取reader把inputStream转换成reader用字符流来读取中文。
bf = new BufferedReader(new InputStreamReader(in));
p.load(bf);
}
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中取不到值时的默认值.
*/
public static String getProperty(String key, String defaultValue)
{
return p.getProperty(key, defaultValue).trim();
}
}