首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Eclipse 英文版保存中文代碼報錯「Cp1251 character encoding」解決方案

     編輯:Java 綜合教學

錯誤現象

Save could not be completed. 
Reason: Some characters cannot be mapped using "Cp1251" character encoding.
Either change the encoding or remove the characters which are not supported by the encoding.

原因:Eclipse 默認文件編碼為系統默認 (中文 Windows 為 GBK,俄文/東歐語系為 Cp1251),保存包含中文字符的文件時編碼不匹配。

方案一:全局設置 UTF-8 (推薦)

  1. Window → Preferences → General → Workspace
  2. 勾選 Text file encoding → Other → UTF-8
  3. 勾選 New text file line delimiter → Unix (跨平台兼容)
  4. Apply and Close → 重啟 Eclipse

方案二:針對 Java Properties 文件單獨設置

  1. Window → Preferences → General → Content Types
  2. 展開 Text → Java Properties File
  3. Default encoding 改為 UTF-8
  4. 點擊 Update → Apply and Close

方案三:項目級強制編碼 (團隊協作推薦)

  1. 右鍵項目 → Properties → Resource
  2. Text file encoding → Other → UTF-8
  3. 此設置寫入 .settings/org.eclipse.core.resources.prefs,提交版本庫,團隊自動同步。

方案四:啟動參數強制 (終極大招)

編輯 eclipse.ini,在 -vmargs 前添加:

// 新建測試類
public class EncodingTest {
    public static void main(String[] args) {
        String s = "中文測試";  // 直接寫中文
        System.out.println(s);
        System.out.println("file.encoding = " + System.getProperty("file.encoding"));
    }
}

運行輸出正常顯示中文且 file.encoding = UTF-8 即成功。

總結

Eclipse 編碼問題本質是 IDE 默認編碼 ≠ 文件實際編碼 ≠ JVM 運行編碼。建議採用 方案三 (項目級 UTF-8) + 方案四 (啟動參數 UTF-8) 雙重保險,並將 .settings 目錄納入版本控制,實現「一鍵導入即正確編碼」的團隊協作體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved