RMS (RecordStore) 僅支援 byte[] 存儲。實際業務常需保存「字符串 + 整數 + 布爾值」等混合類型記錄。本文展示標準序列化/反序列化模式。
public class WriteReadMixedDataTypesExample extends MIDlet implements CommandListener {
private Display display;
private Form form;
private Command cmdExit, cmdStart;
private RecordStore recordStore;
// ... UI 初始化省略
}
try {
recordStore = RecordStore.openRecordStore("myRecordStore", true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
String str = "First Record";
boolean bool = true;
int num = 15;
// 嚴格按順序寫入
dos.writeUTF(str); // 字符串:長度前綴 + Modified UTF-8 字節
dos.writeBoolean(bool); // 1 字節
dos.writeInt(num); // 4 字節,高位在前
dos.flush();
byte[] record = bos.toByteArray();
recordStore.addRecord(record, 0, record.length);
dos.close();
bos.close();
} catch (Exception e) { /* 錯誤處理 */ }
try {
ByteArrayInputStream bis = new ByteArrayInputStream(new byte[100]); // 緩衝區
DataInputStream dis = new DataInputStream(bis);
for (int i = 1; i <= recordStore.getNumRecords(); i++) {
// 讀取記錄到緩衝區
recordStore.getRecord(i, bis, 0); // 注意:bis 實際上需為 byte[],此處簡化
// 正確寫法:
byte[] data = recordStore.getRecord(i);
bis = new ByteArrayInputStream(data);
dis = new DataInputStream(bis);
// **嚴格按寫入順序讀取**
String inStr = dis.readUTF();
boolean inBool = dis.readBoolean();
int inNum = dis.readInt();
// 顯示驗證
Alert alert = new Alert("Reading", inStr + " " + inNum + " " + inBool, null, AlertType.INFO);
display.setCurrent(alert);
dis.close();
bis.close();
}
} catch (Exception e) { /* 錯誤處理 */ }
writeUTF 對應 readUTF,writeInt 對應 readInt,不可混淆close(),避免內存洩漏byte[] 緩衝區,減少 GC// 啟動時打開
recordStore = RecordStore.openRecordStore("myRecordStore", true);
// 退出時關閉並可選刪除
recordStore.closeRecordStore();
if (RecordStore.listRecordStores() != null) {
RecordStore.deleteRecordStore("myRecordStore");
}
setRecord 覆寫,避免刪除重建掌握 DataOutputStream/DataInputStream 配合 ByteArrayOutputStream/ByteArrayInputStream 的模式,是 J2ME 結構化數據持久化的基礎技能。