• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

java 搞代码 4年前 (2022-01-05) 36次浏览 已收录 0个评论

这篇文章主要介绍了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.springframework.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 (IOExc<span style="color:transparent">来源gaodai#ma#com搞*代#码网</span>eption 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

以上就是PropertiesLoaderUtils 出现中文乱码的解决方式的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PropertiesLoaderUtils 出现中文乱码的解决方式

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址