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

用单例模式实现读取xxx.properties文件的内容

2010-09-29 21:14 429 查看
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

import org.apache.log4j.Logger;

/**.
* 鍔熻兘:OVLoadProperties
* @author
*
*/
public class OVLoadProperties {
private static Logger logger = Logger.getLogger(OVLoadProperties.class);
/**
* @param map HashMap
*/
private static HashMap<String, String> map;
/**
* @param instance OVLoadProperties
*/
private static OVLoadProperties instance = null;
/**.
* 鍔熻兘:OVLoadProperties
*/
protected OVLoadProperties() {
}
/**.
* 鍔熻兘:getInstance
* @return OVLoadProperties
*/
public static OVLoadProperties getInstance() {
if (instance == null) {
map = new HashMap();
instance = new OVLoadProperties();
return instance;
}
return instance;
}
/**.
* 鍔熻兘:getProperties
* @param key String
* @return String
*/
public String getProperties(String key) {
return getProperties("xxx.properties", key);
}
/**.
* 鍔熻兘:getProperties
* @param config_file String
* @param key String
* @return String
*/
public String getProperties(String config_file, String key) {

if (map.containsKey(key) == false) {
doGet(config_file, key);
}
return (String) map.get(key);
}
/**.
* 鍔熻兘:doGet
* @param key String
*/
// private void doGet(String key) {
// doGet("config.properties", key);
// }
/**.
* 鍔熻兘:doGet
* @param key String
* @param config_file String
*/
private void doGet(String config_file, String key) {
String a = loadProperties(config_file, key);
map.put(key, a);
}
/**.
* 鍔熻兘:loadProperties
* @param key String
* @return String
*/
// private String loadProperties(String key) {
// String config_file = "xxx.properties";
// return loadProperties(config_file, key);
// }
/**.
* 鍔熻兘:loadProperties
* @param key String
* @param config_file String
* @return String
*/
private String loadProperties(String config_file, String key) {
String result = null;
InputStream is = null;
try {
// support the classpath which including space.
// please DO NOT set "." in your system classpath.
Properties prop = new Properties();
is = OVLoadProperties.class.getClassLoader().getResourceAsStream(config_file);
if(is == null){
is = new FileInputStream(config_file);
}
prop.load(is);

result = prop.getProperty(key);
} catch (Exception e) {
OVLog.writeErrorLog(this.getClass(), e,
"loadProperties failure!", "","");
}finally{
if(is!=null){
try
{
is.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
logger.error("[OVLoadProperties:loadProperties]is close fail");
}
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: