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

Java 中文亂碼終極解決方案:編碼轉換全場景實戰

     編輯:Java 程式設計入門

亂碼根因:編碼不一致

Java 內部使用 UTF-16,外部交互(HTTP、JDBC、文件、控制台)涉及多種編碼。亂碼本質是解碼編碼不匹配:按 ISO-8859-1 讀取了 GBK 字節,或反之。

場景一:JSP/Servlet 頁面輸出

在頁面指令顯式聲明響應編碼:

<%@ page language="java" contentType="text/html; charset=GB2312" pageEncoding="GB2312" %>

或在 Servlet 中:

response.setContentType("text/html;charset=GB2312");
response.setCharacterEncoding("GB2312");

場景二:請求參數獲取(GET/POST 不同)

POST 請求

request.setCharacterEncoding("GB2312"); // 必須在 getParameter 前調用
String name = request.getParameter("name");

GET 請求(Tomcat 8+ 預設 ISO-8859-1)

// 方案一:手動轉碼
String raw = request.getParameter("name");
String name = new String(raw.getBytes("ISO-8859-1"), "GB2312");

// 方案二:配置 server.xml URIEncoding="UTF-8" 統一按 UTF-8 解碼(推薦)

場景三:JDBC 讀寫數據庫

MySQL (Connector/J 5.1+)

jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=GB2312&zeroDateTimeBehavior=convertToNull

Oracle / SQL Server

驅動通常自動處理,若出現亂碼嘗試在連接屬性設定 charSet 或 sendStringParametersAsUnicode。

場景四:文件讀寫與控制台

// 讀取 GBK 文件
try (BufferedReader br = new BufferedReader(
        new InputStreamReader(new FileInputStream("data.txt"), "GBK"))) { ... }

// 寫入 UTF-8 文件
try (BufferedWriter bw = new BufferedWriter(
        new OutputStreamWriter(new FileOutputStream("out.txt"), "UTF-8"))) { ... }

通用轉碼工具類

public final class CharsetUtil {
    public static String convert(String str, String fromCharset, String toCharset) {
        try {
            return new String(str.getBytes(fromCharset), toCharset);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("不支持的編碼", e);
        }
    }
    // 常用組合
    public static String isoToGbk(String s) { return convert(s, "ISO-8859-1", "GBK"); }
    public static String gbkToIso(String s) { return convert(s, "GBK", "ISO-8859-1"); }
}

黃金法則

  1. 全鏈路統一編碼:項目規範 UTF-8(或 GBK),資料庫、連接池、Web 容器、頁面、JS 文件全鏈路一致。
  2. 邊界處理:只有在與外部系統交互(HTTP、文件、舊庫)時才手動轉碼,內部統一用 String(UTF-16)。
  3. 拒絕默認編碼:所有 getBytes()、new String(bytes)、InputStreamReader 必須顯式指定 charset。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved