java读取*.properties配置文件时,中文乱码解决方法

来源:互联网 发布:flotherm软件下载 编辑:程序博客网 时间:2024/06/07 04:00

之前项目中用到的代码块(读取配置文件会乱码):

public class PropertiesConfig {    private static Logger log = Logger.getLogger(PropertiesConfig.class);    public PropertiesConfig() {    }    private static Properties props = new Properties();    static {        try {            props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("propertyconfig.properties"));        } catch (FileNotFoundException e) {            log.error(e);        } catch (IOException e) {            log.error(e);        }    }    public static String getValue(String key) {        return props.getProperty(key);    }}

但是当配置文件中存在如下类型的key=value时,会出现value乱码

user_name=王大力

此时读取到的“王大力“乱码,解决方法(更改静态代码块):

    static {        try {            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("msgconfig.properties");            BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));            props.load(bf);        } catch (FileNotFoundException e) {            log.error(e);        } catch (IOException e) {            log.error(e);        }    }

这样读到的值不会乱码。

0 0
原创粉丝点击