在J2ME中,RMS作为唯一的永久性存储工具,其重要性是不言而喻的。但是很多刚刚开始学习J2ME的新人总是抱怨在这方面的资料很少,或者是针对性不强。因此,我想把自己在这方面的一些学习心得和大家交流一下。 RMS即Record Manager System,在手机应用中常常作为得分记录、游戏信息存储等的工具使用。 RMS的使用可以分为两个部分:一、单一记录的构造;二、RecordStore的使用和操作。下面就这两方面进行详细说明。
一、单一记录的构造。我们在存储记录时可能需要记录很多相似的条目,在这里我们可以把这种结构看成数据库,我们在这一步就是要构造数据库中的一行,即单一记录的构造。程序的源码如下: package com.cuilichen.usual;
import java.io.ByteArrayInputStream;//要使用到的各种输入输出流 import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream;
public class Appointment {//单一记录的类名 private int int1; // private int int2; // private long long1; private String str1; //str1作为保留字段,记录检索的关键字 private String str2; // private String str3; // private boolean WroteFlag; //
public Appointment() { }
public Appointment(int _int1, int _int2, long _long1, String _str1, String _str2, String _str3, boolean _WroteFlag) { this.int1 = _int1; //写入RMS的构造函数 this.int2 = _int2; this.long1 = _long1; this.str1 = _str1; this.str2 = _str2; this.str3 = _str3; this.WroteFlag = _WroteFlag; }
public Appointment(byte[] rec) { initAppointmnet(rec); //读取RMS内容的构造函数 }
public byte[] toBytes() { //写成字节
byte[] data = null;
try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeInt(int1); dos.writeInt(int2); dos.writeLong(long1); dos.writeUTF(str1); dos.writeUTF(str2); dos.writeUTF(str3); dos.writeBoolean(WroteFlag); data = baos.toByteArray(); baos.close(); dos.close(); } catch (Exception e) { e.printStackTrace(); } return data; }
public void initAppointmnet(byte[] rec) { //从字节读取内容
ByteArrayInputStream bais = new ByteArrayInputStream(rec); DataInputStream dis = new DataInputStream(bais);
try { int1 = dis.readInt(); int2 = dis.readInt(); long1 = dis.readLong(); str1 = dis.readUTF(); str2 = dis.readUTF(); str3 = dis.readUTF(); WroteFlag = dis.readBoolean(); } catch (Exception e) { e.printStackTrace(); } }
|
|