读取配置文件properties

java实际开发中,有时候需要读取properties的某个参数值,这个文件一般的命名为:自定义名.properties.

这个可以使用内置的java.util.ResourceBundle解决,这里不作详细解释,请自行百度。

以下方法基于普遍的默认文件自定义名.properties进行编写 深层次的 自定义名_语言代码_国别代码.properties这种标准的properties文件,此处不做考虑

实例:

比如有个文件:file.properties(此文件存放于项目的src根目录,文件编码UTF8),参数如下

test1=12345
test2=abcde

方法逻辑如下:

/**
     * 
     * @param propertyFile 文件名,properties文件(只需名字,无需后缀)
     * @param property 参数名
     * @return 返回参数值
     */
    public static String getString(String propertyFile, String property) {
        ResourceBundle bundle = ResourceBundle.getBundle(propertyFile);
        String value = null;
        try {
            value = bundle.getString(property);
        } catch (MissingResourceException e) {
            value = null;
        }
        return value;
    }

实际运用:

String str = FileUtil.getString("file","test1")
//str值为12345.此处的FileUtil是封装上面方法的工具类,无关紧要


原文地址:https://www.cnblogs.com/codekey/p/4329772.html