1. 程式人生 > >讀取配置檔案的工具類實現

讀取配置檔案的工具類實現

/**
 * 讀取配置檔案的工具類
 * 
 */
public class ConfigManager {
	// 第一步:構建私有的靜態的例項
	private static ConfigManager configManager;
	private static Properties properties;

	// 第二步:建構函式私有化
	private ConfigManager() {
		String configFile = "db.properties";
		properties = new Properties();
		InputStream in = ConfigManager.class.getClassLoader()
				.getResourceAsStream(configFile);
		try {
			properties.load(in);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 第三步:公開一個方法,返回單一例項
	public static ConfigManager getInstance() {
		if (configManager == null) {
			configManager = new ConfigManager();
		}
		return configManager;
	}
	
	/**
	 * 根據key返回value
	 * @param key
	 * @return
	 */
	public String getString(String key) {
		return properties.getProperty(key);
	}

}