J2ME 應用常將文本資源(對白、配置、關卡數據)放入 .txt 文件打包在 JAR 中。但 InputStream 只返回原始字節,編碼轉換全靠開發者手動處理。本文給出 Unicode (LE)、UTF-8、Unicode Big-Endian 三種常見編碼的完整讀取代碼,均支持中英文混排。
每字符 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) {} }
}
直接用 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) {} }
}
使用 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) 處理。文本末尾建議加特殊標記(如 $)判斷結束,避免讀取垃圾數據。
read(buf),避免數據截斷。