在项目中,发现当在配置文件中配置中文的时候,读出来的配置是乱码,这里提供两种解决方案
配置文件:
test.test=\u4f60\u597d
test.test1=你好
第一种:配置文件的值使用Unicode16进制编码
java代码:
@Value("${test.test1}")
String test1;
@Value("${test.test}")
String test;
配置文件配置上面的两个配置项,内容都是“你好”,test.test使用Unicode编码,test.test1直接使用汉字,此时我们在代码中读到的test是正常的,test1是乱码,结果如下:
第二种:指定UTF-8编码读取配置文件
java代码:
Properties config = new Properties();
InputStreamReader is = new InputStreamReader(PropertiesConfig.class.getResourceAsStream("/bootstrap-dev.properties"), "UTF-8");
config.load(is);
log.info("读取配置文件test="+config.getProperty("test.test"));
log.info("读取配置文件test1="+config.getProperty("test.test1"));
这种方式不管上面配置文件写Unicode还是 汉字都能正确读到内容
结果:
建议:汉字的配置使用Unicode16进制编码,因为代码的存储会因为不同的编码也会变成乱码,到时候代码变成乱码就会变得更加麻烦
备注:个人常用的汉字与Unicode编码转换的网址:http://www.msxindl.com/tools/unicode16.asp