J2ME 應用常需讀取本地化文字資源。MIDP 未提供直接的字元流讀取器,需自行處理位元組轉換。本文提供讀取 Unicode (UTF-16BE) 與 UTF-8 編碼檔案的實用工具方法。
Unicode 文字檔通常以 0xFEFF (BOM) 開頭,佔 2 位元組,讀取時需跳過。每個字元佔 2 位元組,高位在前(Big Endian)。
/**
* 讀取 Unicode (UTF-16BE) 編碼文字檔
* @param resource 檔案路徑 (相對 classpath)
* @return 解碼後字串,失敗回傳 null
*/
public static String readUnicode(String resource) {
byte[] buffer = new byte[1024];
InputStream is = null;
try {
is = MyClass.class.getResourceAsStream(resource);
if (is == null) return null;
is.skip(2); // 跳過 BOM
int len = is.read(buffer);
is.close();
StringBuilder sb = new StringBuilder(len / 2);
for (int i = 0; i < len; i += 2) {
int low = buffer[i] & 0xFF;
int high = buffer[i + 1] & 0xFF;
char c = (char) ((high << 8) | low);
sb.append(c);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (is != null) try { is.close(); } catch (IOException ignored) {}
}
}
J2ME String 建構子支援指定編碼,直接將位元組陣列轉換即可。
/**
* 讀取 UTF-8 編碼文字檔
* @param resource 檔案路徑 (相對 classpath)
* @return 解碼後字串,失敗回傳 null
*/
public static String readUTF8(String resource) {
byte[] buffer = new byte[1024];
InputStream is = null;
try {
is = MyClass.class.getResourceAsStream(resource);
if (is == null) return null;
int len = is.read(buffer);
is.close();
return new String(buffer, 0, len, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (is != null) try { is.close(); } catch (IOException ignored) {}
}
}
getResourceAsStream 路徑以 / 開頭表示絕對路徑 (從 JAR 根目錄),不以 / 開頭則相對類別套件。妥善處理編碼讀取,是 J2ME 國際化應用的基石。