温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何解决PropertiesLoaderUtils 中文乱码的问题

发布时间:2020-11-07 16:45:23 来源:亿速云 阅读:394 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关如何解决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

采用如下的配置方式:

<bean id="propertyConifgurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location">
    <value>classpath:evn.properties</value>
  </property>
</bean>

通过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 (IOException ex) {
          if (this.ignoreResourceNotFound) {
            if (logger.isWarnEnabled()) {
              logger.warn("Could not load properties from " + location + ": " + ex.getMessage());
            }
          }
          else {
            throw ex;
          }
        }
      }
    }
  }

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

<bean id="propertyConifgurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location">
    <value>classpath:evn.properties</value>
  </property>
  <property name="fileEncoding">
    <value>utf-8</value>
  </property>
</bean>

看完上述内容,你们对如何解决PropertiesLoaderUtils 中文乱码的问题有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI