在 J2ME 應用中,RMS(Record Management System)是持久化資料的核心機制。本文提供一個採用單例模式封裝的 RmsHelper 類別,簡化資料的讀寫與字串/位元組陣列轉換,適合快速整合至專案中。
DataOutputStream/DataInputStream 實現 UTF-8 編碼的安全轉換。openRecordStore、getRecord、addRecord/setRecord,自動處理記錄不存在或為空的情況。import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.rms.RecordStore;
public class RmsHelper {
private static RmsHelper instance = null;
private RmsHelper() { }
public static synchronized RmsHelper getInstance() {
if (instance == null) {
instance = new RmsHelper();
}
return instance;
}
/** 將字串轉為 UTF-8 位元組陣列 */
public byte[] toBytes(String str) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
try {
dos.writeUTF(str);
dos.flush();
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return new byte[0];
} finally {
try { dos.close(); } catch (Exception ignore) {}
try { baos.close(); } catch (Exception ignore) {}
}
}
/** 將位元組陣列轉回字串 */
public String toString(byte[] data) {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
DataInputStream dis = new DataInputStream(bais);
try {
return dis.readUTF();
} catch (Exception e) {
e.printStackTrace();
return "";
} finally {
try { dis.close(); } catch (Exception ignore) {}
try { bais.close(); } catch (Exception ignore) {}
}
}
/** 讀取指定 RecordStore 的第一筆記錄 */
public String readRecord(String storeName) {
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore(storeName, false, RecordStore.AUTHMODE_ANY, true);
if (rs.getNumRecords() == 0) return "";
return toString(rs.getRecord(1));
} catch (Exception e) {
e.printStackTrace();
return "";
} finally {
closeQuietly(rs);
}
}
/** 儲存字串至 RecordStore(僅保留最新一筆) */
public boolean saveRecord(String storeName, String value) {
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore(storeName, true, RecordStore.AUTHMODE_ANY, true);
byte[] data = toBytes(value);
if (rs.getNumRecords() == 0) {
rs.addRecord(data, 0, data.length);
} else {
rs.setRecord(1, data, 0, data.length);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
closeQuietly(rs);
}
}
private void closeQuietly(RecordStore rs) {
if (rs != null) {
try { rs.closeRecordStore(); } catch (Exception ignore) {}
}
}
}
// 寫入
RmsHelper.getInstance().saveRecord("UserProfile", "userName=John;token=abc123");
// 讀取
String profile = RmsHelper.getInstance().readRecord("UserProfile");
此工具類已處理例外與資源釋放,可直接複製到專案中使用,若需支援多筆記錄,可自行擴充 enumerateRecords 相關邏輯。