java读取properties文件内容并解决中文内容乱码问题

java读取properties文件内容方式有多种,这里记录自己使用的方式。

一、使用Resource

public static String getPropertiesValueByName(String name){
    Resource re = new ClassPathResource("db.properties");
    Properties p = null;
    try{
        p = PropertiesLoaderUtils.loadProperties(re);
    }catch(IOException e){
        e.printStackTrace();
    }
    String value = StringUtils.trim(p.getProperty(name));
    return value;
}

这里Resource接口属于org.springframework.core.io包,PropertiesLoaderUtils类属于org.springframework.core.in.support包。

二、使用java.lang包的class变量的getResourceAsStream()方法(解决中文乱码)

public static String getPropertiesValueByName(String name){
    Properties p = new Properties();
    InputStream in = this.getClass().getResourceAsStream("db.properties");
    try{
        BufferedReader bf = new BufferedReader(new InputStreamReader(in, "utf-8"));//不加utf-8的话会导致中文value乱码
        p.load(bf);
    }catch(IOException e){
        e.printStackTrace();
    }
    String value = StringUtils.trim(p.getProperty(name));
    return value;
}

在读取的时候采用BufferedReader去读取。加了utf-8之后取出的中文值不再是乱码。

你可能感兴趣的:(java读取properties文件内容并解决中文内容乱码问题)