PropertiesLoaderUtils 出现中文乱码的解决方式
我就废话不多说了,大家还是直接看代码吧~
try
{
EncodedResourceencodedResource=newEncodedResource(newClassPathResource(path),Charsets.UTF_8);
Propertiesproperties=PropertiesLoaderUtils.loadProperties(encodedResource);
}
catch(IOExceptione)
{
LOGGER.info("Champion:readpropertiesfailure",e);
}
补充知识:使用SpringPropertyPlaceholderConfigurer配置中文出现乱码的解决方法
问题描述
在使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer读取配置文件时,发现对于中文的处理会出现乱码现象,比如有如下的配置项及其内容:
content.shell=#!/bin/bash\necho"test,测试一下!!"\nsleep$1
采用如下的配置方式:
classpath:evn.properties
通过Spring获取到的配置项内容,中文变成了乱码。
解决方法
通过了解类org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的继承关系,发现父类org.springframework.core.io.support.PropertiesLoaderSupport中有这样的属性fileEncoding,这一属性的使用是在loadProperties方法中:
/**
*Loadpropertiesintothegiveninstance.
*@parampropsthePropertiesinstancetoloadinto
*@throwsIOExceptionincaseofI/Oerrors
*@see#setLocations
*/
protectedvoidloadProperties(Propertiesprops)throwsIOException{
if(this.locations!=null){
for(Resourcelocation:this.locations){
if(logger.isInfoEnabled()){
logger.info("Loadingpropertiesfilefrom"+location);
}
try{
PropertiesLoaderUtils.fillProperties(
props,newEncodedResource(location,this.fileEncoding),this.propertiesPersister);
}
catch(IOExceptionex){
if(this.ignoreResourceNotFound){
if(logger.isWarnEnabled()){
logger.warn("Couldnotloadpropertiesfrom"+location+":"+ex.getMessage());
}
}
else{
throwex;
}
}
}
}
}
通过添加fileEncoding=utf-8属性可以解决上述问题:
classpath:evn.properties utf-8
以上这篇PropertiesLoaderUtils出现中文乱码的解决方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。