Springboot從配置文件properties讀取字符串亂碼的解決
從配置文件properties讀取字符串亂碼
當讀取properties的內容為:發(fā)現(xiàn)中文亂碼。原因是由于默認讀取的為ISO-8859-1格式,因此需要切換為UTF-8。
主要方式有如下兩種:
方式一
在你的application.properties中增加如下配置,避免中文亂碼
spring.http.encoding.enabled=true
方法二
在你的settings里面的File Encodings進行更改為如圖1.1 中紅框。

圖1.1
properties文件的屬性值為中文,讀取時亂碼
我們在開發(fā)中使用properties文件時,常會遇到這樣的問題,比如說:
test.property.value=中文值
我們想把屬性值設置成中文,這樣無論使用@value還是直接讀取出來會出現(xiàn)亂碼,總結了兩種解決方案如下:
把屬性值直接轉成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;
@Slf4j
public 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"));
}
}以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot 并發(fā)登錄人數(shù)控制的實現(xiàn)方法
這篇文章主要介紹了SpringBoot 并發(fā)登錄人數(shù)控制的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-05-05
Redisson分布式閉鎖RCountDownLatch的使用詳細講解
分布式鎖和我們java基礎中學習到的synchronized略有不同,synchronized中我們的鎖是個對象,當前系統(tǒng)部署在不同的服務實例上,單純使用synchronized或者lock已經無法滿足對庫存一致性的判斷。本次主要講解基于rediss實現(xiàn)的分布式鎖2023-02-02
使用Java實現(xiàn)動態(tài)生成MySQL數(shù)據(jù)庫
這篇文章主要為大家詳細介紹了如何使用Java實現(xiàn)動態(tài)生成MySQL數(shù)據(jù)庫,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-02-02

