J2ME 專案常將字串資源存為文字檔置於 JAR 內,透過 getResourceAsStream 讀取。但 InputStream 僅回傳原始位元組,需依編碼手動解碼。本文提供三種常見編碼(Unicode LE、UTF-8、Unicode BE)的完整讀取方法,均支援中英文混合內容。
src/ 或 res/,打包進 JAR 根目錄或同包路徑。readUni("/data.txt")、readUTF("/data.txt")、readUniBE("/data.txt")。Windows 記事本另存為「Unicode」預設產生此格式(含 BOM FF FE)。讀取時需跳過 BOM,並將低位在前的兩個位元組組合為 char。
private String readUni(String res) {
byte[] buf = new byte[1024];
StringBuffer sb = new StringBuffer();
InputStream is = null;
try {
is = getClass().getResourceAsStream(res);
int len = is.read(buf);
// 跳過 BOM (FF FE)
int start = (len >= 2 && buf[0] == (byte)0xFF && buf[1] == (byte)0xFE) ? 2 : 0;
for (int i = start; i + 1 < len; i += 2) {
int low = buf[i] & 0xFF;
int high = buf[i+1] & 0xFF;
sb.append((char)(low | (high << 8)));
}
} catch (Exception e) { e.printStackTrace(); }
finally { try { if (is != null) is.close(); } catch (Exception ignore) {} }
return sb.toString();
}
最通用、無 BOM(或可選 EF BB BF),J2ME String 建構子直接支援 "UTF-8" 解碼。
public String readUTF(String res) {
byte[] buf = new byte[1024];
InputStream is = null;
try {
is = getClass().getResourceAsStream(res);
int len = is.read(buf);
// 若有 BOM 則略過前 3 bytes
int start = (len >= 3 && buf[0]==(byte)0xEF && buf[1]==(byte)0xBB && buf[2]==(byte)0xBF) ? 3 : 0;
return new String(buf, start, len - start, "UTF-8");
} catch (Exception e) {
System.out.println("readUTF Error: " + e);
return "";
} finally {
try { if (is != null) is.close(); } catch (Exception ignore) {}
}
}
記事本另存為「Unicode big endian」產生(BOM FE FF)。使用 DataInputStream.readChar() 直接讀取大端序 char,需跳過 BOM 兩字節。
private String readUniBE(String res) {
char[] buf = new char[1024];
int count = 0;
DataInputStream dis = null;
try {
dis = new DataInputStream(getClass().getResourceAsStream(res));
dis.skipBytes(2); // 跳過 FE FF
while (true) {
char c = dis.readChar();
if (c == '$') break; // 約定 '$' 為結束標記
if (count < buf.length) buf[count++] = c;
}
} catch (Exception e) {
System.out.println("readUniBE error: " + e.getMessage());
} finally {
try { if (dis != null) dis.close(); } catch (Exception ignore) {}
}
return String.valueOf(buf, 0, count);
}
| 編碼 | 適用場景 | 檔案大小 | 備註 |
|---|---|---|---|
| UTF-8 | 跨平台、以 ASCII 為主、含中文 | 最小 | 推薦首選,J2ME 內建支援 |
| Unicode LE | Windows 記事本預設、需頻繁在 PC 編輯 | 2× ASCII | 讀取需手動處理 BOM 與位序 |
| Unicode BE | Java 內部預設大端序、配合 DataInputStream | 2× ASCII | 需約定結束標記或預知長度 |