萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Eclipse 設定 UTF-8 編碼完整指南:Workspace、專案、檔案層級全覆蓋

為什麼要統一 UTF-8?

  • 國際化支援:中文、日文、韓文、Emoji 等完整 Unicode 字元
  • 避免中文亂碼:GBK/Big5 互轉導致資料損壞
  • 團隊協作一致性:跨平台 (Windows/macOS/Linux) 統一編碼
  • 現代標準:JSON、XML、HTML5、資料庫連線預設皆為 UTF-8

層級 1:Workspace 全域預設 (影響新專案)

Window → Preferences → General → Workspace
→ Text file encoding: Other → UTF-8
→ New text file line delimiter: Unix (LF) 推薦

注意:僅對**新建立**的專案生效,既有專案不受影響。

層級 2:內容類型關聯 (針對特定副檔名)

Window → Preferences → General → Content Types
→ Text → Java Source File (或 JSP, XML, Properties, CSS, JS 等)
→ Default encoding: UTF-8 → Update
  • Java Source File:源碼檔
  • JSP File:JSP 頁面
  • XML File:XML 設定檔
  • Properties File:資源包 (注意:Java 標準規範為 ISO-8859-1,但現代框架支援 UTF-8,建議統一 UTF-8 並用 `native2ascii` 或 IDE 自動轉換)

層級 3:專案層級覆蓋 (最高優先權)

專案右鍵 → Properties → Resource
→ Text file encoding: Other → UTF-8

此設定儲存於專案目錄 `.settings/org.eclipse.core.resources.prefs`,提交版控可共享給團隊。

層級 4:檔案層級 (個別檔案)

檔案右鍵 → Properties → Resource
→ Text file encoding: Other → UTF-8

主控台輸出編碼 (Run/Debug 時)

Run → Run Configurations → Common → Encoding: UTF-8
或
-Dfile.encoding=UTF-8 (VM Arguments)

Maven/Gradle 專案編碼設定

<!-- pom.xml -->
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.11.0</version>
    <configuration>
        <encoding>UTF-8</encoding>
    </configuration>
</plugin>
// build.gradle
tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}
compileJava.options.encoding = 'UTF-8'

常見亂碼場景排查表

一鍵檢查腳本 (專案根目錄執行)

#!/bin/bash
# check_encoding.sh
echo "=== 檢查 Java 檔案編碼 ==="
find . -name "*.java" -exec file -i {} \; | grep -v "utf-8"

echo "=== 檢查 XML/JSP/Properties 編碼 ==="
find . \( -name "*.xml" -o -name "*.jsp" -o -name "*.properties" \) -exec file -i {} \; | grep -v "utf-8"

echo "=== 檢查 .settings 編碼設定 ==="
cat .settings/org.eclipse.core.resources.prefs 2>/dev/null | grep -i encoding

總結:建議設定順序

  1. Workspace 全域 → UTF-8
  2. Content Types 關鍵類型 → UTF-8
  3. 專案 Properties → UTF-8 (提交版控)
  4. Maven/Gradle build 編碼 → UTF-8
  5. Run Config 主控台 → UTF-8
  6. Tomcat/資料庫連線 → UTF-8

完成上述設定,專案中文亂碼問題可徹底解決。

copyright © 萬盛學電腦網 all rights reserved
現象可能原因解決
主控台輸出亂碼Run Configuration 編碼非 UTF-8設定 Common → Encoding: UTF-8
JSP 頁面中文亂碼JSP 指令缺失或 Tomcat URIEncoding`<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>` + `server.xml URIEncoding="UTF-8"`
資料庫中文亂碼連線字串無 characterEncodingJDBC URL: `?characterEncoding=utf8&useUnicode=true`
Git 提交檔案編碼不一缺 `.gitattributes`加入 `* text=auto eol=lf` 或 `*.java text eol=lf`
Properties 檔中文變 \uXXXXJava 標準為 ISO-8859-1IDE 設定 UTF-8 並啟用「透明轉換」,或用 YAML/JSON 替代