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

J2ME 讀取 Unicode 與 UTF-8 編碼文件完整實現方案

     編輯:J2ME

前言:J2ME 文件讀取的編碼挑戰

J2ME 運行環境多樣、資源嚴格受限,標準 java.io 子集未提供完整的字元集轉換器。讀取 Unicode (UTF-16) 與 UTF-8 文本文件時,需自行處理 BOM、位元序與解碼邏輯。本文提供兩個可直接用於生產的工具方法。

一、讀取 Unicode (UTF-16) 文件

關鍵點

  • Unicode 文本文件開頭通常有 2 字節 BOM(0xFE 0xFF 大端、0xFF 0xFE 小端),需跳過。
  • CLDC 無 DataInputStream.readChar(),需手動組合高低位元組。
  • 假設文件為大端序(網路標準序),若為小端需交換高低位組合邏輯。

完整代碼


public static String read_Uni(String resource) {
    byte[] word_uni = new byte[1024];
    String strReturn = null;
    InputStream is = null;
    try {
        is = MyMidlet.class.getResourceAsStream(resource);
        is.skip(2); // 跳過 BOM
        is.read(word_uni);
        is.close();

        StringBuffer stringbuffer = new StringBuffer("");
        for (int j = 0; j < word_uni.length; ) {
            int l = word_uni[j++] & 0xFF;
            int h = word_uni[j++] & 0xFF;
            char c = (char) ((l) | (h << 8)); // 大端序:高位在前
            stringbuffer.append(c);
        }
        strReturn = stringbuffer.toString();
    } catch (IOException ex) {
        System.out.println(ex);
    } finally {
        is = null;
    }
    return strReturn;
}

注意:若文件為小端序(Windows 常見),組合邏輯應改為 (h | (l << 8))。實際專案中建議檢測 BOM 自動判斷位元序。

二、讀取 UTF-8 文件

優勢

CLDC 1.1+ 的 new String(byte[], "UTF-8") 內建支援 UTF-8 解碼,無需手動解析多位元組序列,代碼極簡。

完整代碼


public static String read_UTF(String resource) {
    byte[] word_utf = new byte[1024];
    String strReturn = null;
    InputStream is = null;
    try {
        is = MyMidlet.class.getResourceAsStream(resource);
        is.read(word_utf);
        is.close();
        strReturn = new String(word_utf, "UTF-8");
    } catch (IOException ex) {
        System.out.println(ex);
    } finally {
        is = null;
    }
    return strReturn;
}

工程化建議

  1. 緩衝區大小動態化:1024 位元組僅為示例,實際應依文件大小分配或分塊讀取。
  2. 資源路徑:getResourceAsStream 路徑相對於 JAR 根目錄,以 / 開頭(如 /data/config.txt)。
  3. 異常處理:生產代碼應拋出或記錄具體異常,避免靜默失敗。
  4. 編碼檢測:若編碼不確定,可先讀取前幾位元組檢測 BOM(UTF-8: EF BB BF;UTF-16BE: FE FF;UTF-16LE: FF FE)自動分派解碼器。

結語

J2ME 讀取多編碼文本的核心在於:Unicode 需手動組合雙位元組(注意位元序),UTF-8 可直接借助 VM 內建解碼器。封裝為通用工具類並加入編碼自動檢測,即可滿足多數嵌入式應用的本地化配置與資源讀取需求。

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