Java读取Properties配置文件

来源:互联网 发布:园林设计软件下载 编辑:程序博客网 时间:2024/06/16 02:19

目录

1.Properties类与Properties配置文件
2.Properties中的主要方法
3.示例

1.Properties类与Properties配置文件

Properties类继承自Hashtable类并且实现了Map接口,使用键值对的形式来保存属性集。不过Properties的键和值都是字符串类型。

2.Properties中的主要方法

(1)load(InputStream inStream)
此方法可以从.properties属性文件对应的文件输入流中,加载属性列表到Properties类对象。用于读取Properties配置文件。

Properties prop = new Properties(); //读取属性文件a.propertiesInputStream 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);

这样操作就方便多了。
[参考]

  1. 旭东的博客
  2. 《架构探险》——黄勇