J2ME (CLDC/MIDP) 核心類庫精簡,java.io 僅支援 InputStream/OutputStream 位元組流,**無 Reader/Writer 字元流**,亦無 String(byte[], String charset) 建構子 (MIDP 2.0 才補充)。讀取文本檔需自行處理位元組→字串解碼。本文提供 Unicode (UTF-16BE) 與 UTF-8 兩種常見編碼的讀取工具方法。
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;
}
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,需實作 RFC 3629 解碼邏輯:
((b0&0x1F)<<6) | (b1&0x3F)((b0&0x0F)<<12) | ((b1&0x3F)<<6) | (b2&0x3F)代碼篇幅較長,建議封裝為 Utf8Decoder 工具類,或採用 ProGuard 預處理 將 UTF-8 文本編譯期轉為 Unicode 字串常量 (最推薦)。
native2ascii 或自定 Task 將 UTF-8 文本轉為 Unicode .properties 或 .java 常量類src/ 同層級 resources/,打包進 JAR 根目錄,getResourceAsStream("/filename") 訪問J2ME 讀取文本核心是 InputStream → ByteArrayOutputStream → 位元組陣列 → 手工/系統解碼為 String。優先選 Unicode 資源格式簡化運行期邏輯;MIDP 2.0 可直接用 new String(bytes, "UTF-8");MIDP 1.0 強烈建議編譯期預處理避開運行期解碼複雜度。