解决 properties.getProperty() 字符串中文乱码的情况

时间:2020-04-04 23:40:03   收藏:0   阅读:340

一、情况

程序中通过读取 properties 配置文件来完成设置参数等功能,但是当配置文件中存在中文时,再通过以下(错误示范)代码进行读取并取值时,当值为中文时,则中文乱码(英文等字符不受影响)

// 错误示范代码
Properties properties = new Properties();
InputStream inputStream = TestClass.class.getResourceAsStream("/ScreenShotParams.properties");
properties.load(inputStream);
String saveLocationDir = properties.getProperty("saveLocationDir");

LOGGER.info("saveLocationDir:" + saveLocationDir);

二、分析

InputStream 字节流来读取中文字符,肯定乱码啦,改用字符流试试?

三、解决

// 正确代码
Properties properties = new Properties();
InputStream inputStream = TestClass.class.getResourceAsStream("/ScreenShotParams.properties");
InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
BufferedReader br = new BufferedReader(isr);
// 一定一定要 load 设置编码后的字符流
properties.load(br);
String saveLocationDir = properties.getProperty("saveLocationDir");

LOGGER.info("saveLocationDir:" + saveLocationDir);

按以上正确代码读取配置时,仍中文乱码的情况时

四、知识点

原文:https://www.cnblogs.com/zhiyin1209/p/12633902.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!