首页 > 技术文章 > 读取java配置文件properties

lhb68 2019-01-15 15:07 原文

java项目里很多参数都是写在配置文件properties上,如果需要读取的话,可以使用jdk里提供的Properties类进行处理。

具体写法如下:

public class PropertiesCfg {
    
    //配置文件所在目录路径,相对项目根目录,如果是放在根目录下,直接写文件名称就行
    private final static String file = "config/myproperties.properties";
    private final static Properties properties = new Properties();
    
    static{
        try {
            properties.load(new InputStreamReader(ClassLoader.getSystemResourceAsStream(file),"utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //根据key获取值
    public static  String get(String key){
        return properties.getProperty(key).trim();
    }
    
    //根据key获取值,值为空则返回defaultValue
    public static  String get(String key,String defaultValue){
        return properties.getProperty(key, defaultValue);
    }

该工具类已经使用编码格式化了中文字符,可以正常读取中文的。

另外,配置文件写法一般都是xxxkey=xxxvalue,通过=分割开,其实还可以用空格,冒号隔开的。如下:

name=王大
account account1
age:3

测试代码:

public class Main {

    public static void main(String[] args) {
        System.out.println(PropertiesCfg.get("name"));        
        System.out.println(PropertiesCfg.get("account"));
        System.out.println(PropertiesCfg.get("age"));
    }
}

 

再另外,在eclipse上创建properties后缀的文件,默认是ISO-8859-1格式的,在此格式下写入中文字符,会自动转成Unicode编码的字符,如:你好啊 会转成 \u4F60\u597D\u554A。这样子并不是乱码,而且是可以正常读取的,只是不方便进行阅读。如果不想自动转,就把配置文件的格式改成utf-8就好了。

右键选中配置文件,点击【properties】,在打开的界面上修改格式即可。如下图

 

推荐阅读