承接上篇高階 UI 基礎,本文實作通訊錄應用,示範 RMS 本地儲存與 GCF 網路存取兩大核心功能,並對比 StreamConnection 與 ContentConnection 差異。
RecordStore) 以位元組陣列為單位,欄位解析由開發者自行實作| 介面/類別 | 用途 |
|---|---|
RecordStore | 開啟/建立/刪除/寫入/讀取記錄存儲 |
RecordEnumeration | 雙向游標遍歷記錄 (最常用) |
RecordComparator | 自訂排序比較 |
RecordFilter | 自訂過濾條件 |
RecordListener | 記錄變更事件通知 |
public class AddressDB {
private static RecordStore rs;
public AddressDB() {
try { rs = RecordStore.openRecordStore("addressbook", true); }
catch (RecordStoreException e) { e.printStackTrace(); }
}
// 新增:姓名+地址以 UTF 編碼存入
public void addAddress(String name, String addr) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
dos.writeUTF(name + "," + addr);
byte[] data = bos.toByteArray();
rs.addRecord(data, 0, data.length);
} catch (Exception e) { e.printStackTrace(); }
}
// 取得第 index 筆姓名 (1-based)
public static String getName(int index) {
try {
RecordEnumeration re = rs.enumerateRecords(null, null, false);
int cnt = 1;
while (cnt <= index && re.hasNextElement()) {
String rec = new String(re.nextRecord());
int comma = rec.indexOf(',');
if (cnt == index) return rec.substring(2, comma); // 跳過 UTF 長度前綴
cnt++;
}
} catch (Exception e) { e.printStackTrace(); }
return null;
}
// getAddress(index) 同理
// recordCount() 回傳 rs.getNumRecords()
}
List (IMPLICIT 模式) 顯示姓名清單TextBox 顯示完整姓名/地址Command.BACK 自動對應返回鍵,Command.STOP 對應結束
Connector.open("https://host/file") → 回傳實作 Connection 介面的物件
StreamConnection conn = (StreamConnection) Connector.open(url);
InputStream in = conn.openInputStream();
byte[] buf = new byte[255]; // 必須猜測大小 ⚠️
int len = in.read(buf);
String data = new String(buf, 0, len).trim();
// 後續用 StringTokenizer 解析 (J2ME 無內建,需自行實作或移植)
ContentConnection conn = (ContentConnection) Connector.open(url);
int len = (int) conn.getLength(); // 精確取得內容長度 ✅
byte[] buf = new byte[len];
InputStream in = conn.openInputStream();
in.read(buf); // 一次讀完
// 解析邏輯相同
配合 HttpConnection 可實作 SOAP、XML-RPC、RSS/Atom 解析,構建豐富網路應用。
| 功能 | 本地 RMS | 網路 GCF |
|---|---|---|
| 儲存單位 | 位元組陣列/記錄 | 串流/內容連線 |
| 查詢 | RecordEnumeration + 自訂 Filter/Comparator | HTTP GET/POST + XML/JSON 解析 |
| 同步 | 需自行實作同步邏輯 | 原生支援 Client-Server 架構 |
| 適用場景 | 離線快取、設定、小量資料 | 即時資料、大量資料、多使用者 |