J2ME 運行環境多樣、資源嚴格受限,標準 java.io 子集未提供完整的字元集轉換器。讀取 Unicode (UTF-16) 與 UTF-8 文本文件時,需自行處理 BOM、位元序與解碼邏輯。本文提供兩個可直接用於生產的工具方法。
0xFE 0xFF 大端、0xFF 0xFE 小端),需跳過。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 自動判斷位元序。
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;
}
getResourceAsStream 路徑相對於 JAR 根目錄,以 / 開頭(如 /data/config.txt)。J2ME 讀取多編碼文本的核心在於:Unicode 需手動組合雙位元組(注意位元序),UTF-8 可直接借助 VM 內建解碼器。封裝為通用工具類並加入編碼自動檢測,即可滿足多數嵌入式應用的本地化配置與資源讀取需求。