在windows環(huán)境,vscode+java擴(kuò)展+spring擴(kuò)展搭建Java開發(fā)環(huán)境時(shí),經(jīng)常出現(xiàn)中文亂碼的問題。其實(shí)出現(xiàn)中文亂碼的問題,通常是由于cmd或者powershell環(huán)境字符集和java源碼字符集不匹配導(dǎo)致。
windows環(huán)境默認(rèn)字符集未GBK,而vscode編輯的Java源碼文件默認(rèn)字符集是UTF-8。
要解決亂碼問題,只要保證Java運(yùn)行時(shí)、powershell(或者cmd)以及Java源碼字符集保持一致就可以。
1、vscode啟動(dòng)java程序時(shí),指定-Dfile.encoding參數(shù)為UTF-8
1、點(diǎn)擊vscode左側(cè)的“運(yùn)行和調(diào)試”圖標(biāo):
運(yùn)行和調(diào)試
2、選擇啟動(dòng)項(xiàng)右側(cè)的設(shè)置圖標(biāo):

右側(cè)設(shè)置圖標(biāo)
3、在右側(cè)編輯區(qū)域打開launch.json文件,在啟動(dòng)項(xiàng)中編輯encoding項(xiàng)的值:
{
"configurations": [
{
"type": "java",
"name": "Spring Boot-EurekaServerApp<eureka>",
"request": "launch",
"cwd": "${workspaceFolder}",
"mainClass": "com.example.eureka.EurekaServerApp",
"projectName": "eureka",
"args": "",
"envFile": "${workspaceFolder}/.env",
"encoding": "UTF-8"
}
]
}
如果配置項(xiàng)中沒有encoding配置項(xiàng),則添加該配置項(xiàng)。
2、設(shè)置powershell環(huán)境的字符集為UTF-8
1、點(diǎn)擊vscode左下角的設(shè)置圖標(biāo),選擇彈出菜單中的“設(shè)置”菜單項(xiàng):
設(shè)置
2、點(diǎn)擊settings.json編輯器右上角的“打開設(shè)置(json)”按鈕,打開settings.json編輯器:

打開設(shè)置圖標(biāo)
3、在settings.xml文件中添加配置項(xiàng):
{
"terminal.integrated.profiles.windows": {
"PowerShell": {
"source": "PowerShell",
"icon": "terminal-powershell",
"args": ["-NoExit", "/c", "chcp 65001"]
},
"Command Prompt": {
"path": [
"${env:windir}\\Sysnative\\cmd.exe",
"${env:windir}\\System32\\cmd.exe",
"args": ["-NoExit", "/c", "chcp 65001"]
],
"args": ["-NoExit", "/c", "chcp 65001"],
"icon": "terminal-cmd"
},
"Git Bash": {
"source": "Git Bash"
}
}
}
在powershell配置項(xiàng)中添加args配置項(xiàng),其中-NoExit是啟動(dòng)后不自動(dòng)關(guān)閉的意思,chcp 65001是powershell后,將運(yùn)行環(huán)境的字符集修改為UTF-8,65001是windows環(huán)境UTF-8字符集的code page代碼。