欢迎来到代码驿站!

当前位置:首页 >

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

时间:2020-08-22 18:00:08|栏目:|点击:

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

   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>

上一篇:使用Java 8 Lambda表达式将实体映射到DTO的操作

栏    目:

下一篇:R语言ggplot2边框背景去除的实现

本文标题:PropertiesLoaderUtils 出现中文乱码的解决方式

本文地址:http://www.codeinn.net/misctech/3913.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有