核心技术:J2ME中RMS的使用解析(转)

核心技术:J2ME中RMS的使用解析(转)(@more@)在J2ME中,RMS作为唯一的永久性存储工具,其重要性是不言而喻的。但是很多刚刚开始学习J2ME的新人总是抱怨在这方面的资料很少,或者是针对性不强,因此,我想把自己在这方面的一些学习心得和大家交流一下。

RMS即记录管理系统,在手机应用中常常作为得分记录,游戏信息存储等的工具使用。
RMS的使用可以分为两个部分:一,单一记录的构造;二,RecordStore的使用和操作。下面就这两方面进行详细说明。

一、单一记录的构造。我们在存储记录时可能需要记录很多相似的条目,在这里我们可以把这种结构看成数据库,我们在这一步就是要构造数据库中的一行,即单一记录的构造。程序的源码如下:
包com.cuilichen.usual;

进口java.io.ByteArrayInputStream;//要使用到的各种输入输出流
进口java.io.ByteArrayOutputStream;
进口java.io.DataInputStream;
进口java.io.DataOutputStream;

公共类任命{//单一记录的类名
私人int int1;//
私人int int2;//
私人长long1;
私人字符串str1;//str1作为保留字段,记录检索的关键字
私人字符串str2;//
私人字符串str3;//
私人布尔WroteFlag;//

公开任命(){}


公开任命(int _int1, int _int2、_long1长、弦_str1 _str2
字符串,字符串_str3,布尔_WroteFlag) {
this.int1=_int1;//写入RMS的构造函数
this.int2=_int2;
。long1=_long1;
。str1=_str1;
。str2=_str2;
。str3=_str3;
。WroteFlag=_WroteFlag;
}

公共任命(byte [] rec) {
initAppointmnet (rec);//读取RMS内容的构造函数
}

公共byte [] toBytes(){//写成字节

byte []=https://www.yisu.com/zixun/null的数据;

尝试{
ByteArrayOutputStream包=new ByteArrayOutputStream ();
DataOutputStream dos=new DataOutputStream(包);
dos.writeInt (int1);
dos.writeInt (int2);
dos.writeLong (long1);
dos.writeUTF (str1);
dos.writeUTF (str2);
dos.writeUTF (str3);
dos.writeBoolean (WroteFlag);
data=https://www.yisu.com/zixun/baos.toByteArray ();
baos.close ();
dos.close ();
}捕捉(异常e) {
e.printStackTrace ();

}返回数据;
}

公共空initAppointmnet (byte [] rec){//从字节读取内容

ByteArrayInputStream姨=new ByteArrayInputStream (rec);
DataInputStream说=new DataInputStream(姨);

尝试{
int1=dis.readInt ();
int2=dis.readInt ();
long1=dis.readLong ();
str1=dis.readUTF ();
str2=dis.readUTF ();
str3=dis.readUTF ();
WroteFlag=dis.readBoolean ();
}捕捉(异常e) {
e.printStackTrace ();

}}
公共int getInt1 () {//int
返回int1;

}公共int getInt2 () {
返回int2;

}公共长getLong1 () {
返回long1;
}

公共字符串getStr1(){//字符串
返回str1;
}

公共字符串getStr2(){//字符串
返回str2;
}

公共字符串getStr3 () {
返回str3;
}

公共布尔getWroteFlag(){//返回写入标志
返回WroteFlag;

}}
这个类的使用保证了我们在使用流时,内容的写入和输出。当然,就如同数据库表的设计一样,我们可以任意对每一条记录增加或减少字段,在上面的类中我只使用了int1, int2, long1, str1, str2, str3和WroteFlag一共7个字段。

二,RecordStore的操作。类RMS如下:
包com.cuilichen.usual;

进口javax.microedition.rms.RecordEnumeration;
进口javax.microedition.rms.RecordStore;

公共类RMS {
公共静态最终int Int1=0;//各个字段的默认数值
公共静态最终int Int2=0;
公共静态最终长Long1=0;
公共静态最终字符串Str1=" ";
公共静态最终字符串Str2=" ";
公共静态最终字符串Str3=" ";

公共静态布尔addRecord(字符串名称、int int1 int int2,//添加记录
长long1字符串str1,字符串str2,字符串str3,布尔b) {
布尔成功=false;

{
RecordStore rs=RecordStore试试。openRecordStore(名字、真实);
任命程序=新约会(int1、int2 long1, str1, str2, str3, b);
//既然str1作为保留字段,我们在这里就要如此操作,例如int1为我们设定的关键字,那么str1=Integer.toString (int1);
byte [] data=https://www.yisu.com/zixun/app.toBytes ();
rs。addRecord(数据、0 data.length);
rs.closeRecordStore ();
成功=true;
}捕捉(异常e) {
e.printStackTrace ();

}返回成功;

}公共静态int getNumOfRecords(字符串名称){//得到RMS中记录的条数
{
RecordStore rs=RecordStore试试。openRecordStore(名字、真实);

返回rs.getNumRecords ();
}捕捉(异常e) {
返回0;

}}

公共静态任命[]getRecords(字符串名称){//取得RMS中的所有记录
任命[]结果={};

{

核心技术:J2ME中RMS的使用解析(转)