Record Management System (RMS) 是 MIDP 提供的持久化存儲機制,面向字節數組而非結構化字段。核心概念:
byte[] 的數據(文本、圖片、對象等)。javax.microedition.rms.RecordStore 實現。MIDlet-Data-Size(單位 byte)。AUTHMODE_PRIVATE/PUBLIC)實現跨套件共享。J2ME 無原生對象序列化,需手工實現。核心類:
ByteArrayOutputStream / ByteArrayInputStream:內存緩衝區 ↔ 字節數組。DataOutputStream / DataInputStream:按基本類型/UTF 字符串讀寫。public class MyByteArrayOutputStream extends ByteArrayOutputStream {
public byte[] getByteArray() { return buf; } // 直接返回內部緩衝區
}
public class Bank {
private String bankName, phone;
private int employeeNum;
public byte[] serialize() throws IOException {
MyByteArrayOutputStream bos = new MyByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeUTF(bankName);
dos.writeUTF(phone);
dos.writeInt(employeeNum);
dos.flush();
return bos.getByteArray();
}
public static Bank deserialize(byte[] data) throws IOException {
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
Bank b = new Bank();
b.bankName = dis.readUTF();
b.phone = dis.readUTF();
b.employeeNum = dis.readInt();
return b;
}
}
// 打開/創建
RecordStore rs = RecordStore.openRecordStore("MyStore", true);
// 寫入
byte[] data = bank.serialize();
rs.addRecord(data, 0, data.length);
// 讀取(遍歷)
RecordEnumeration re = rs.enumerateRecords(null, null, false);
while (re.hasNextElement()) {
byte[] rec = re.nextRecord();
Bank b = Bank.deserialize(rec);
}
// 更新/刪除
rs.setRecord(recordId, newData, 0, newData.length);
rs.deleteRecord(recordId);
// 關閉
rs.closeRecordStore();
RecordStoreFullException」的測試 MIDlet,實測真機可用上限(如文中 Nokia 6108 僅 31KB)。RecordStoreException、RecordStoreFullException、RecordStoreNotFoundException 分類處理。version 字段,反序列化時按版本兼容解析。RMS 雖輕量但功能完備,掌握「字節流序列化 + RecordStore CRUD + 配額管理 + 線程同步」四大塊,即可應對絕大多數 J2ME 本地存儲需求。