Java讀取Properties設定檔Demo,支援中文__Java

來源:互聯網
上載者:User
要讀取的設定檔config.properties(UTF-8格式)

##姓名name=張三#年齡age=31#性別sex=男

Java代碼

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();}}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.