Springboot从配置文件properties读取字符串乱码的解决

目录

  • 从配置文件properties读取字符串乱码
    • 方式一
    • 方法二
  • properties文件的属性值为中文,读取时乱码
    • 把属性值直接转成unicode编码
    • 在方法中转码

从配置文件properties读取字符串乱码 当读取properties的内容为:发现中文乱码。原因是由于默认读取的为ISO-8859-1格式,因此需要切换为UTF-8。
【Springboot从配置文件properties读取字符串乱码的解决】主要方式有如下两种:

方式一
在你的application.properties中增加如下配置,避免中文乱码
spring.http.encoding.enabled=true


方法二
在你的settings里面的File Encodings进行更改为如图1.1 中红框。
Springboot从配置文件properties读取字符串乱码的解决
文章图片

图1.1

properties文件的属性值为中文,读取时乱码 我们在开发中使用properties文件时,常会遇到这样的问题,比如说:
test.property.value=https://www.it610.com/article/中文值

我们想把属性值设置成中文,这样无论使用@value还是直接读取出来会出现乱码,总结了两种解决方案如下:

把属性值直接转成unicode编码
写在文件中,如:
test.property.value.unicode=\u4e2d\u6587\u503c


在方法中转码
如下面代码中的getChinese()方法
package com.xiaobai.util; import lombok.extern.slf4j.Slf4j; import java.io.UnsupportedEncodingException; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; @Slf4jpublic class PropertiesUtil { protected static ResourceBundle erpResponse; protected static final String PROPERTIES_FILE = "propertytest"; static {try {erpResponse = PropertyResourceBundle.getBundle(PROPERTIES_FILE); } catch (Exception e) {log.error(PROPERTIES_FILE + "配置文件加载失败。", e); }} public static String get(String key) {return erpResponse.getString(key); } public static String getChinese(String key) {String string = null; try {string = new String(erpResponse.getString(key).getBytes("ISO-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) {log.error(e.getMessage()); }return string; } public static void main(String[] args) {//属性值直接写成中文,打印出来的结果:??-???System.out.println(get("test.property.value")); //解决方案一,使用转码的方式,打印结果:中文值System.out.println(getChinese("test.property.value")); //解决方案二,properties文件中的属性值写成unicode(\u4e2d\u6587\u503c),打印结果:中文值System.out.println(get("test.property.value.unicode")); } }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读