PropertiesLoaderUtils 出现中文乱码的解决方式

网友投稿 381 2022-11-25


PropertiesLoaderUtils 出现中文乱码的解决方式

我就废话不多说了,大家还是直接看代码吧~

try

{

EncodedResource encodedResource = new EncodedResource(new ClassPathResource(path), Charsets.UTF_8);

Properties properties = PropertiesLoaderUtils.loadProperties(encodedResource);

}

catch (IOException e)

{

LOGGER.info("Champion:read properties failure",e);

}

补充知识:使用Spring PropertyPlaceholderConfigurer 配置中文出现乱码的解决方法

问题描述

在使用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.sprinjtnxHCUzigframework.core.io.support.PropertiesLoaderSupport中有这样的属性fileEncoding,这一属性的使用是在loadProperties方法中:

/**

* Load properties into the given instance.

* @param props the Properties instance to load into

* @throws IOException in case of I/O errors

* @see #setLocations

*/

protected void loadProperties(Properties props) throws IOException {

if (this.locations != null) {

for (Resource location : this.locations) {

if (logger.isInfoEnabled()) {

logger.info("Loading properties file from " + location);

}

try {

PropertiesLoaderUtils.fillProperties(

props, new EncodedResource(location, this.fileEncoding), this.propertiesPersister);

}

catch (IOException ex) {

if (this.ignoreResourceNotFound) {

if (logger.isWarnEnabled()) {

logger.warn("Could not load properties from " + location + ": " + ex.getMessage());

}

}

else {

throw ex;

}

}

}

}

}

通过添加fileEncoding=utf-8属性可以解决上述问题:

classpath:evn.properties

utf-8


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Springboot实现根据条件切换注入不同实现类的示例代码
下一篇:java注解之运行时修改字段的注解值操作
相关文章

 发表评论

暂时没有评论,来抢沙发吧~