1. 程式人生 > >Java讀取Properties配置檔案Demo,支援中文

Java讀取Properties配置檔案Demo,支援中文

package com.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * 從properties配置中取值並列印日誌,注意:讀取完畢要手動呼叫close方法.
 *
 * @author chichuduxing
 * @date 2017年2月14日 下午1:45:28
 */

public class PropertiesUtils {
	/**
	 * 日誌物件.
	 */
	private static final Logger logger = Logger.getLogger(PropertiesUtils.class);

	/**
	 * 檔名稱
	 */
	private String _confName;

	private InputStream _inputStream;
	private Properties _properties;

	public PropertiesUtils(String confpath) {
		this._confName = confpath;
	}

	public void init() throws Exception {
		_inputStream = new FileInputStream(_confName);
		_properties = new Properties();
		_properties.load(new InputStreamReader(_inputStream, "UTF-8"));
	}

	/**
	 * 從配置中取值.
	 *
	 * @param key
	 *            取值的key
	 * @return
	 */
	private String getTrimValue(String key) {
		String tmp = _properties.getProperty(key);
		if (null == tmp) {
			return StringUtils.EMPTY;
		} else {
			return tmp.trim();
		}
	}

	/**
	 * 取可為空的字串.
	 *
	 * @param key
	 *            取值key
	 * @return ""/trim後的結果
	 */
	public String getStringEnEmpty(String key) {
		String tmp = getTrimValue(key);
		logger.info("Read [" + key + "] ==> [" + tmp + "]");
		return tmp;
	}

	/**
	 * 取不可為空字串.
	 *
	 * @param key
	 *            取值key
	 * @return ""/trim後的結果
	 * @throws Exception
	 *             取得結果為空.
	 */
	public String getStringDisEmpty(String key) throws Exception {
		String tmp = getTrimValue(key);
		logger.info("Read [" + key + "] ==> [" + tmp + "]");
		if (tmp.isEmpty()) {
			throw new Exception("[" + key + "] value is Empty!");
		}
		return tmp;
	}

	/**
	 * 取字串格式的預設值.
	 *
	 * @param key
	 *            取值key,不為null即可
	 * @param defaultvalue
	 *            預設值,可為null
	 */
	public String getStringValue(String key, String defaultvalue) {
		String tmp = getTrimValue(key);
		if (StringUtils.isEmpty(tmp)) {
			logger.info("Read [" + key + "] ==> [" + tmp + "] isEmpty,use defalut value:[" + defaultvalue + "]");
			tmp = defaultvalue;
		} else {
			logger.info("Read [" + key + "] ==> [" + tmp + "]");
		}
		return tmp;
	}

	/**
	 * 取整形,為空或者不合法會丟擲異常.
	 *
	 * @param key
	 * @param defalutvalue
	 * @return
	 */
	public int getIntValue(String key) {
		String tmpvalue = getTrimValue(key);
		int num = 0;
		num = Integer.parseInt(tmpvalue);
		logger.info("Read [" + key + "] ==> [" + num + "]");
		return num;
	}

	/**
	 * 取整形,帶預設值.取不到或者不合法則取預設值
	 *
	 * @param key
	 * @param defalutvalue
	 * @return
	 */
	public int getIntValue(String key, int defalutvalue) {
		String tmpvalue = getTrimValue(key);
		int num = 0;
		try {
			num = Integer.parseInt(tmpvalue);
			logger.info("Read [" + key + "] ==> [" + num + "]");
		} catch (Exception e) {
			num = defalutvalue;
			logger.warn("Read [" + key + "] ==> [" + tmpvalue + "] ,use default value:[" + num + "]");
		}
		return num;
	}

	/**
	 * 取範圍內的值.
	 *
	 * @param key
	 *            取值的key.
	 * @param minnum
	 *            允許的最小值.
	 * @param maxnum
	 *            允許的最大值.
	 * @return
	 * @throws Exception
	 *             不是數字/範圍不合法.
	 */
	public int getIntValue(String key, int minnum, int maxnum) throws Exception {
		String tmpvalue = getTrimValue(key);
		int num = 0;
		try {
			num = Integer.parseInt(tmpvalue);
			if (num >= minnum && num <= maxnum) {
				// 合法則到此結束.
				logger.info("Read [" + key + "] ==> [" + num + "]");
				return num;
			}
		} catch (Exception e) {
		}
		throw new Exception("Read [" + key + "] ==> [" + tmpvalue + "] not in [" + minnum + "," + maxnum + "]");
	}

	/**
	 * 取長整形,帶預設值.
	 *
	 * @param key
	 * @param defalutvalue
	 * @return
	 */
	public long getLongValue(String key, long defalutvalue) {
		String tmpvalue = getTrimValue(key);
		long num = 0;
		try {
			num = Long.parseLong(tmpvalue);
			logger.info("Read [" + key + "] ==> [" + num + "]");
		} catch (Exception e) {
			num = defalutvalue;
			logger.warn("Read [" + key + "] ==> [" + tmpvalue + "] ,use default value:[" + num + "]");
		}
		return num;
	}

	/**
	 * 取範圍內的值.
	 *
	 * @param key
	 *            取值的key.
	 * @param minnum
	 *            允許的最小值.
	 * @param maxnum
	 *            允許的最大值.
	 * @return
	 * @throws Exception
	 *             不是數字/範圍不合法.
	 */
	public long getLongValue(String key, long minnum, long maxnum) throws Exception {
		String tmpvalue = getTrimValue(key);
		long num = 0;
		try {
			num = Long.parseLong(tmpvalue);
			if (num >= minnum && num <= maxnum) {
				// 合法則到此結束.
				logger.info("Read [" + key + "] ==> [" + num + "]");
				return num;
			}
		} catch (Exception e) {
		}
		throw new Exception("Read [" + key + "] ==> [" + tmpvalue + "] not in [" + minnum + "," + maxnum + "]");
	}

	/**
	 * 關閉檔案流,需要手動關閉!
	 */
	public void close() {
		if (null != _inputStream) {
			try {
				_inputStream.close();
			} catch (IOException e) {
			}
		}
	}

	public static void main(String[] args) {
		PropertiesUtils proputil = new PropertiesUtils("conf/config.properties");
		try {
			proputil.init();
			// 取key為"key1"的值,取不到則預設為"all"
			proputil.getStringValue("key1", "all");
			// 取key為"name"的值,該值不能為空
			proputil.getStringDisEmpty("name");

			proputil.getIntValue("age");

			proputil.getStringEnEmpty("sex");
		} catch (Exception e) {
			e.printStackTrace();
			// 配置檔案讀取異常,程式退出
			return;
		} finally {

			// 記得呼叫close方法
			proputil.close();
		}
	}

}