栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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方法中:

  
  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
  


以上这篇PropertiesLoaderUtils 出现中文乱码的解决方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/132369.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号