一、前言
许多时候,系统都需要一个配置文件,重复编写这些配置文件读取程序很烦恼,又浪费时间 ,下面给一个通用的方法
二、方法论
好吧!我们用一个简单的单例模式来解决这个问题,一般来说配置文件都是加载一次就够了,最简单的单例模式(实践比空谈好)
1、私有静态对象
private static Config cfg = null;
2、构造器私有化
private Config() {
properties = new Properties();
InputStream is = null;
try {
is = Config.class.getResourceAsStream(path);
properties.load(is);
} catch (Exception exception) {
System.out.println("Can't read the properties file. ");
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
3、公有静态创建方法
public static Config getInstance() {
if (cfg == null) {
cfg = new Config();
}
return cfg;
}
public static Config getInstance(String path) {
path =path;
if (cfg == null) {
cfg = new Config();
}
return cfg;
}
三、代码
package common.utils;
import common.log.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author chenhaipeng
* @version 1.0
* @date 2014/12/04 17:25
*/
public class Config {
private Properties properties;
private static Config cfg = null;
private String path = "/config/config.properties";
private final static String ERR_MSG = "从配置文件中不能取得传入参数的返回值:";
private Config() {
properties = new Properties();
InputStream is = null;
try {
is = Config.class.getResourceAsStream(path);
properties.load(is);
} catch (Exception exception) {
System.out.println("Can't read the properties file. ");
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
public static Config getInstance() {
if (cfg == null) {
cfg = new Config();
}
return cfg;
}
public static Config getInstance(String path) {
path =path;
if (cfg == null) {
cfg = new Config();
}
return cfg;
}
/**
* Retun a value for certain key.
*
* @param key a certain key define in properties file.
* @return value
*/
public String getValue(String key) {
if (!properties.containsKey(key))
return null;
String value = properties.getProperty(key);
if (value == null) {
Log.getLogger().error(ERR_MSG + ":" + key);
}
return value;
}
public static void main(String args[]) {
System.out.println(Config.getInstance("/config/test.properties").getValue("DB.DRIVER"));
// System.out.println(Thread.currentThread().getContextClassLoader().);
}
}