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

J2ME 中文傳輸解決方案:Unicode 編碼與 ISO-8859-1 轉換

     編輯:J2ME

J2ME 應用與伺服器交換中文資料時,需解決編碼不一致問題。本文提供雙向轉換完整程式碼。

伺服器 → 客戶端:GB2312 轉 Unicode (\uXXXX)

// 伺服器端寫入
public static void writeUnicode(DataOutputStream out, String value) throws ActionException {
    try {
        String unicode = StringFormatter.gbEncoding(value);
        byte[] data = unicode.getBytes();
        out.writeInt(data.length);
        out.write(data, 0, data.length);
    } catch (IOException e) {
        throw new ActionException(IMDefaultAction.class.getName(), e.getMessage());
    }
}

// gbEncoding 實作:雙位元組字元轉 \uXXXX,ASCII 前補 00
public static String gbEncoding(String gbString) {
    char[] utfBytes = gbString.toCharArray();
    StringBuilder unicodeBytes = new StringBuilder();
    for (char c : utfBytes) {
        String hexB = Integer.toHexString(c);
        if (hexB.length() <= 2) hexB = "00" + hexB;
        unicodeBytes.append("\\u").append(hexB);
    }
    return unicodeBytes.toString();
}

// 客戶端解碼
private StringBuffer decodeUnicode(String dataStr) {
    StringBuffer buffer = new StringBuffer();
    int start = 0, end;
    while (start > -1) {
        end = dataStr.indexOf("\\u", start + 2);
        String charStr = (end == -1) 
            ? dataStr.substring(start + 2) 
            : dataStr.substring(start + 2, end);
        char letter = (char) Integer.parseInt(charStr, 16);
        buffer.append(letter);
        start = end;
    }
    return buffer;
}

客戶端 → 伺服器:ISO-8859-1 傳輸

// 客戶端發送
private void writeSjis(DataOutputStream outData, String value) {
    try {
        byte[] data = value.getBytes("ISO8859_1");
        outData.writeInt(data.length);
        outData.write(data, 0, data.length);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

// 伺服器端接收並轉 UTF-8
public static String isoToUtf(String iso) {
    if (iso == null) return "";
    try {
        return new String(iso.getBytes("ISO-8859-1"), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return iso;
    }
}

注意:此法需手機支援 Unicode/GB2312 編碼。資料庫存取時仍需依具體 DB 內碼再轉換。

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