
package cn.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ConfigManager {
//读取jdbc.properties配置文件,单例模式
private static ConfigManager configManager;
private static Properties properties;
//单例模式必须用private构造方法,不能用public
private ConfigManager(){
String configFile = "jdbc.properties";
properties = new Properties();
InputStream is = ConfigManager.class.getClassLoader().getResourceAsStream(configFile);
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
}
//提供一个入口获取ConfigManager,这个方法可以严格控制实例生成的个数
public static ConfigManager getInstance(){
//如果为空就创建一个自已的构造方法,获取ConfigManager
if(configManager == null){
configManager = new ConfigManager();
}
return configManager;
}
//以上只是获取了properties的KEY值,下面这个方法获取对应的value值
public String getString (String key){
return properties.getProperty(key);
}
}
Properties类的重要方法
Properties类在 Java.util 中,该类继承自 Hashtable
1. getProperty ( String key) , 用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
2. load ( InputStream inStream) ,从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文
件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。
3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
4. store ( OutputStream out, String comments) , 以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素
对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
5. clear () ,清除所有装载的 键 - 值对。该方法在基类中提供。
原文:http://www.cnblogs.com/bboymonk/p/6000534.html