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

J2ME 讀取 Unicode 與 UTF-8 編碼文件工具類

     編輯:J2ME

前言

J2ME (CLDC/MIDP) 核心類庫精簡,java.io 僅支援 InputStream/OutputStream 位元組流,**無 Reader/Writer 字元流**,亦無 String(byte[], String charset) 建構子 (MIDP 2.0 才補充)。讀取文本檔需自行處理位元組→字串解碼。本文提供 Unicode (UTF-16BE) 與 UTF-8 兩種常見編碼的讀取工具方法。

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

Unicode 文本通常以 UTF-16BE (Big Endian) 儲存:每字元 2 位元組,高位在前。讀取邏輯:逐對位元組組合為 char。

/**
 * 讀取 Unicode (UTF-16BE) 編碼文本資源
 * @param resource 資源路徑 (如 "/data/text.uni")
 * @return 解碼後字串,失敗返回 null
 */
public static String readUnicode(String resource) {
    String result = null;
    InputStream is = null;
    try {
        is = MyMidlet.class.getResourceAsStream(resource);
        if (is == null) return null;

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len = is.read(buf)) != -1) {
            bos.write(buf, 0, len);
        }
        byte[] data = bos.toByteArray();

        // 位元組陣列 → char 陣列 (Big Endian)
        char[] chars = new char[data.length / 2];
        for (int i = 0, j = 0; i < data.length; i += 2, j++) {
            int high = data[i] & 0xFF;
            int low  = data[i + 1] & 0xFF;
            chars[j] = (char)((high << 8) | low);
        }
        result = new String(chars);
    } catch (IOException e) {
        System.err.println("Read Unicode failed: " + e);
    } finally {
        try { if (is != null) is.close(); } catch (IOException ignored) {}
    }
    return result;
}

二、讀取 UTF-8 編碼文件

MIDP 2.0+ 支援 new String(bytes, "UTF-8")。MIDP 1.0 需手工解碼 (較複雜),建議**統一使用 Unicode 儲存資源**,或要求 MIDP 2.0 環境。

/**
 * 讀取 UTF-8 編碼文本資源 (需 MIDP 2.0 / CLDC 1.1)
 * @param resource 資源路徑
 * @return 解碼後字串
 */
public static String readUTF8(String resource) {
    InputStream is = null;
    try {
        is = MyMidlet.class.getResourceAsStream(resource);
        if (is == null) return null;

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len = is.read(buf)) != -1) {
            bos.write(buf, 0, len);
        }
        // MIDP 2.0 直接支援 UTF-8 解碼
        return new String(bos.toByteArray(), "UTF-8");
    } catch (IOException e) {
        System.err.println("Read UTF-8 failed: " + e);
        return null;
    } finally {
        try { if (is != null) is.close(); } catch (IOException ignored) {}
    }
}

MIDP 1.0 環境下的 UTF-8 手工解碼 (補充)

若必須在 MIDP 1.0 解碼 UTF-8,需實作 RFC 3629 解碼邏輯:

  • 單位元組 (0x00~0x7F) → 直接對應 ASCII
  • 雙位元組 (0xC0~0xDF 開頭) → ((b0&0x1F)<<6) | (b1&0x3F)
  • 三位元組 (0xE0~0xEF 開頭) → ((b0&0x0F)<<12) | ((b1&0x3F)<<6) | (b2&0x3F)

代碼篇幅較長,建議封裝為 Utf8Decoder 工具類,或採用 ProGuard 預處理 將 UTF-8 文本編譯期轉為 Unicode 字串常量 (最推薦)。

最佳實踐建議

  1. 資源檔統一存為 UTF-16BE (Unicode):Java 內部即 char[],讀取最簡單高效,無編碼相容問題
  2. 編譯期轉換:建構腳本 (Ant/Maven) 中以 native2ascii 或自定 Task 將 UTF-8 文本轉為 Unicode .properties 或 .java 常量類
  3. 大文本分塊載入:避免一次性載入超大文本導致 OOM,採用分頁/流式讀取
  4. 資源路徑:置於 src/ 同層級 resources/,打包進 JAR 根目錄,getResourceAsStream("/filename") 訪問

總結

J2ME 讀取文本核心是 InputStream → ByteArrayOutputStream → 位元組陣列 → 手工/系統解碼為 String。優先選 Unicode 資源格式簡化運行期邏輯;MIDP 2.0 可直接用 new String(bytes, "UTF-8");MIDP 1.0 強烈建議編譯期預處理避開運行期解碼複雜度。

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