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

J2ME 讀取文字資源檔:Unicode、UTF-8、Unicode Big Endian 三種編碼完整處理

     編輯:J2ME

J2ME 專案常將字串資源存為文字檔置於 JAR 內,透過 getResourceAsStream 讀取。但 InputStream 僅回傳原始位元組,需依編碼手動解碼。本文提供三種常見編碼(Unicode LE、UTF-8、Unicode BE)的完整讀取方法,均支援中英文混合內容。

共同前置條件

  • 資源檔置於 src/ 或 res/,打包進 JAR 根目錄或同包路徑。
  • 呼叫方式:readUni("/data.txt")、readUTF("/data.txt")、readUniBE("/data.txt")。
  • 緩衝陣列大小視檔案長度調整,範例以 1024 字元/位元組為示意。

1. Unicode Little Endian (UTF-16LE)

Windows 記事本另存為「Unicode」預設產生此格式(含 BOM FF FE)。讀取時需跳過 BOM,並將低位在前的兩個位元組組合為 char。

private String readUni(String res) {
    byte[] buf = new byte[1024];
    StringBuffer sb = new StringBuffer();
    InputStream is = null;
    try {
        is = getClass().getResourceAsStream(res);
        int len = is.read(buf);
        // 跳過 BOM (FF FE)
        int start = (len >= 2 && buf[0] == (byte)0xFF && buf[1] == (byte)0xFE) ? 2 : 0;
        for (int i = start; i + 1 < len; i += 2) {
            int low = buf[i] & 0xFF;
            int high = buf[i+1] & 0xFF;
            sb.append((char)(low | (high << 8)));
        }
    } catch (Exception e) { e.printStackTrace(); }
    finally { try { if (is != null) is.close(); } catch (Exception ignore) {} }
    return sb.toString();
}

2. UTF-8

最通用、無 BOM(或可選 EF BB BF),J2ME String 建構子直接支援 "UTF-8" 解碼。

public String readUTF(String res) {
    byte[] buf = new byte[1024];
    InputStream is = null;
    try {
        is = getClass().getResourceAsStream(res);
        int len = is.read(buf);
        // 若有 BOM 則略過前 3 bytes
        int start = (len >= 3 && buf[0]==(byte)0xEF && buf[1]==(byte)0xBB && buf[2]==(byte)0xBF) ? 3 : 0;
        return new String(buf, start, len - start, "UTF-8");
    } catch (Exception e) {
        System.out.println("readUTF Error: " + e);
        return "";
    } finally {
        try { if (is != null) is.close(); } catch (Exception ignore) {}
    }
}

3. Unicode Big Endian (UTF-16BE)

記事本另存為「Unicode big endian」產生(BOM FE FF)。使用 DataInputStream.readChar() 直接讀取大端序 char,需跳過 BOM 兩字節。

private String readUniBE(String res) {
    char[] buf = new char[1024];
    int count = 0;
    DataInputStream dis = null;
    try {
        dis = new DataInputStream(getClass().getResourceAsStream(res));
        dis.skipBytes(2); // 跳過 FE FF
        while (true) {
            char c = dis.readChar();
            if (c == '$') break; // 約定 '$' 為結束標記
            if (count < buf.length) buf[count++] = c;
        }
    } catch (Exception e) {
        System.out.println("readUniBE error: " + e.getMessage());
    } finally {
        try { if (dis != null) dis.close(); } catch (Exception ignore) {}
    }
    return String.valueOf(buf, 0, count);
}

選擇建議

進階提示

  • 大檔案請分塊讀取(while((len=is.read(buf))!=-1)),避免 OOM。
  • 若資源檔固定不變,可考慮預先在建構階段用工具轉為 byte[] 直接內嵌於程式碼,省去執行時解碼開銷。
  • 統一專案編碼為 UTF-8,可大幅簡化程式碼與維護成本。

三種讀取方法已封裝為可直接複製的工具方法,按專案實際編碼選用即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
編碼適用場景檔案大小備註
UTF-8跨平台、以 ASCII 為主、含中文最小推薦首選,J2ME 內建支援
Unicode LEWindows 記事本預設、需頻繁在 PC 編輯2× ASCII讀取需手動處理 BOM 與位序
Unicode BEJava 內部預設大端序、配合 DataInputStream2× ASCII需約定結束標記或預知長度