首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2ME

J2ME RMS 混合數據類型讀寫實戰:DataOutputStream/DataInputStream 完整範例

     編輯:J2ME

場景

RMS (RecordStore) 僅支援 byte[] 存儲。實際業務常需保存「字符串 + 整數 + 布爾值」等混合類型記錄。本文展示標準序列化/反序列化模式。

核心類結構

public class WriteReadMixedDataTypesExample extends MIDlet implements CommandListener {
    private Display display;
    private Form form;
    private Command cmdExit, cmdStart;
    private RecordStore recordStore;
    // ... UI 初始化省略
}

寫入流程:ByteArrayOutputStream + DataOutputStream

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) { /* 錯誤處理 */ }

讀取流程:ByteArrayInputStream + DataInputStream

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) { /* 錯誤處理 */ }

關鍵規則總結

  1. 順序一致性:讀取順序必須與寫入順序完全一致
  2. 類型匹配:writeUTF 對應 readUTF,writeInt 對應 readInt,不可混淆
  3. 流管理:用完及時 close(),避免內存洩漏
  4. 異常保護:RMS 操作均需 try-catch,防止存儲滿、記錄存不存在等錯誤
  5. 緩衝區複用:讀取循環中可複用 byte[] 緩衝區,減少 GC

完整生命週期管理

// 啟動時打開
recordStore = RecordStore.openRecordStore("myRecordStore", true);

// 退出時關閉並可選刪除
recordStore.closeRecordStore();
if (RecordStore.listRecordStores() != null) {
    RecordStore.deleteRecordStore("myRecordStore");
}

進階應用提示

  • 記錄結構版本化:首字節存版本號,支持格式演進
  • 定長記錄優化:固定結構可直接 setRecord 覆寫,避免刪除重建
  • 索引加速:大量記錄時維護單獨索引文件(關鍵字→記錄 ID)
  • 加密敏感數據:寫入前 AES/XOR 加密字節數組

掌握 DataOutputStream/DataInputStream 配合 ByteArrayOutputStream/ByteArrayInputStream 的模式,是 J2ME 結構化數據持久化的基礎技能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved