Java讀取Properties配置文件

1.Properties類與Properties配置文件

Properties類繼承自Hashtable類而且實現了Map接口,使用鍵值對的形式來保存屬性集。不過Properties的鍵和值都是字符串類型。html

2.Properties中的主要方法

(1)load(InputStream inStream)
此方法能夠從.properties屬性文件對應的文件輸入流中,加載屬性列表到Properties類對象。用於讀取Properties配置文件。架構

Properties prop = new Properties(); 
//讀取屬性文件a.properties
InputStream in = new BufferedInputStream (new FileInputStream("a.properties"));
prop.load(in);     ///加載屬性列表
Iterator<String> it=prop.stringPropertyNames().iterator();
while(it.hasNext()){
    String key=it.next();
    System.out.println(key+":"+prop.getProperty(key));
}
in.close();

(2)store(OutputStream out, String comments)
此方法將Properties類對象的屬性列表保存到輸出流中。用於寫Properties配置文件。工具

Properties prop = new Properties(); 
//保存屬性到b.properties文件
FileOutputStream oFile = new FileOutputStream("b.properties", true);//true表示追加打開
prop.setProperty("phone", "10086");
prop.store(oFile, "Comment");//若是comments不爲空,保存後的屬性文件第一行會是#comments,表示註釋信息;若是爲空則沒有註釋信息。註釋信息後面是屬性文件的當前保存時間信息。
oFile.close();

(3)getProperty/setProperty
這兩個方法是分別是獲取和設置屬性信息。code

3.示例

下面是黃勇老師寫的獲取屬性文件的工具類。orm

/**
 * 屬性文件工具類
 */
public final class PropsUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(PropsUtil.class);

    /**
     * 加載屬性文件
     */
    public static Properties loadProps(String fileName) {
        Properties props = null;
        InputStream is = null;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            if (is == null) {
                throw new FileNotFoundException(fileName + " file is not found");
            }
            props = new Properties();
            props.load(is);
        } catch (IOException e) {
            LOGGER.error("load properties file failure", e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error("close input stream failure", e);
                }
            }
        }
        return props;
    }

    /**
     * 獲取字符型屬性(默認值爲空字符串)
     */
    public static String getString(Properties props, String key) {
        return getString(props, key, "");
    }

    /**
     * 獲取字符型屬性(可指定默認值)
     */
    public static String getString(Properties props, String key, String defaultValue) {
        String value = defaultValue;
        if (props.containsKey(key)) {
            value = props.getProperty(key);
        }
        return value;
    }

    /**
     * 獲取數值型屬性(默認值爲 0)
     */
    public static int getInt(Properties props, String key) {
        return getInt(props, key, 0);
    }

    // 獲取數值型屬性(可指定默認值)
    public static int getInt(Properties props, String key, int defaultValue) {
        int value = defaultValue;
        if (props.containsKey(key)) {
            value = CastUtil.castInt(props.getProperty(key));
        }
        return value;
    }

    /**
     * 獲取布爾型屬性(默認值爲 false)
     */
    public static boolean getBoolean(Properties props, String key) {
        return getBoolean(props, key, false);
    }

    /**
     * 獲取布爾型屬性(可指定默認值)
     */
    public static boolean getBoolean(Properties props, String key, boolean defaultValue) {
        boolean value = defaultValue;
        if (props.containsKey(key)) {
            value = CastUtil.castBoolean(props.getProperty(key));
        }
        return value;
    }
}

裏面用到了CastUtil類,該類是爲了處理一些數據轉型操做而準備的,代碼以下:htm

/**
 * 轉型操做工具類
 */
public final class CastUtil {

    /**
     * 轉爲 String 型
     */
    public static String castString(Object obj) {
        return CastUtil.castString(obj, "");
    }

    /**
     * 轉爲 String 型(提供默認值)
     */
    public static String castString(Object obj, String defaultValue) {
        return obj != null ? String.valueOf(obj) : defaultValue;
    }

    /**
     * 轉爲 double 型
     */
    public static double castDouble(Object obj) {
        return CastUtil.castDouble(obj, 0);
    }

    /**
     * 轉爲 double 型(提供默認值)
     */
    public static double castDouble(Object obj, double defaultValue) {
        double doubleValue = defaultValue;
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    doubleValue = Double.parseDouble(strValue);
                } catch (NumberFormatException e) {
                    doubleValue = defaultValue;
                }
            }
        }
        return doubleValue;
    }

    /**
     * 轉爲 long 型
     */
    public static long castLong(Object obj) {
        return CastUtil.castLong(obj, 0);
    }

    /**
     * 轉爲 long 型(提供默認值)
     */
    public static long castLong(Object obj, long defaultValue) {
        long longValue = defaultValue;
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    longValue = Long.parseLong(strValue);
                } catch (NumberFormatException e) {
                    longValue = defaultValue;
                }
            }
        }
        return longValue;
    }

    /**
     * 轉爲 int 型
     */
    public static int castInt(Object obj) {
        return CastUtil.castInt(obj, 0);
    }

    /**
     * 轉爲 int 型(提供默認值)
     */
    public static int castInt(Object obj, int defaultValue) {
        int intValue = defaultValue;
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    intValue = Integer.parseInt(strValue);
                } catch (NumberFormatException e) {
                    intValue = defaultValue;
                }
            }
        }
        return intValue;
    }

    /**
     * 轉爲 boolean 型
     */
    public static boolean castBoolean(Object obj) {
        return CastUtil.castBoolean(obj, false);
    }

    /**
     * 轉爲 boolean 型(提供默認值)
     */
    public static boolean castBoolean(Object obj, boolean defaultValue) {
        boolean booleanValue = defaultValue;
        if (obj != null) {
            booleanValue = Boolean.parseBoolean(castString(obj));
        }
        return booleanValue;
    }
}

castUtil類中用到了StringUtil類,它提供一些字符串操做,代碼以下:對象

/**
 * 字符串工具類
 */
public final class StringUtil {

    /**
     * 判斷字符串是否爲空
     */
    public static boolean isEmpty(String str) {
        if (str != null) {
            str = str.trim();
        }
        return StringUtils.isEmpty(str);
    }

    /**
     * 判斷字符串是否非空
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }
}

這樣就能夠直接運用這個工具類操做Properties配置文件了。
操做示例(獲取一個int屬性的值,並給一個默認值1):blog

Properties conf = PropsUtil.loadProps("config.properties");
int value = PropsUtil.getInt(conf,"key",1);

這樣操做就方便多了。
[參考]繼承

  1. 旭東的博客
  2. 《架構探險》——黃勇
相關文章
相關標籤/搜索