1. 程式人生 > >Java讀取Properties配置文件

Java讀取Properties配置文件

配置文件 java 字符串 接口

1.Properties類與Properties配置文件

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

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
這兩個方法是分別是獲取和設置屬性信息。

3.示例

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

/**
 * 屬性文件工具類
 */
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類,該類是為了處理一些數據轉型操作而準備的,代碼如下:

/**
 * 轉型操作工具類
 */
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):

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

這樣操作就方便多了。


Java讀取Properties配置文件