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

J2ME 讀取多種編碼文本文件完整方案(Unicode/UTF-8/Big-Endian)

     編輯:J2ME

解決 J2ME 資源文件中文亂碼:三種編碼讀取方法對比

J2ME 應用常將文本資源(對白、配置、關卡數據)放入 .txt 文件打包在 JAR 中。但 InputStream 只返回原始字節,編碼轉換全靠開發者手動處理。本文給出 Unicode (LE)、UTF-8、Unicode Big-Endian 三種常見編碼的完整讀取代碼,均支持中英文混排。

1. Unicode Little-Endian (無 BOM 或 FF FE 開頭)

每字符 2 字節,低位在前。逐字節讀取並組合:

private String readUnicodeLE(String res) {
    byte[] buf = new byte[1024];
    InputStream is = null;
    try {
        is = getClass().getResourceAsStream(res);
        is.read(buf);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; ) {
            int lo = buf[i++] & 0xFF;
            int hi = buf[i++] & 0xFF;
            char c = (char) (lo | (hi << 8));
            if (c == 0) break; // 遇 \0 視為結束
            sb.append(c);
        }
        return sb.toString();
    } catch (IOException e) { e.printStackTrace(); return ""; }
    finally { try { if (is != null) is.close(); } catch (Exception ignore) {} }
}

2. UTF-8 (推薦,兼容性最好)

直接用 new String(bytes, "UTF-8"),J2ME 實現需包含 microedition.encoding.UTF-8 系統屬性(大多數手機支持):

public String readUTF8(String res) {
    InputStream is = null;
    byte[] buf = new byte[1024];
    try {
        is = getClass().getResourceAsStream(res);
        is.read(buf);
        return new String(buf, "UTF-8").trim(); // trim 去除尾部填充 \0
    } catch (Exception e) { System.out.println("UTF-8 read error: " + e); return ""; }
    finally { try { if (is != null) is.close(); } catch (Exception ignore) {} }
}

3. Unicode Big-Endian (FE FF 開頭,記事本默認保存格式)

使用 DataInputStream.readChar() 直接讀取 16 位字符,需跳過開頭 2 字節 BOM:

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

注意:記事本保存的「Unicode」即 Big-Endian 帶 BOM。用 UltraEdit 另存為可去除 BOM,或代碼中 skipBytes(2) 處理。文本末尾建議加特殊標記(如 $)判斷結束,避免讀取垃圾數據。

測試環境與建議

  • 測試平台:Windows XP + Sun WTK 2.2 DefaultColorPhone
  • 實際項目中建議統一使用 UTF-8 無 BOM 编碼保存文本,代碼最簡潔、跨平台兼容性最強。
  • 若文件較大(>1KB),請改用循環分塊讀取而非一次性 read(buf),避免數據截斷。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved