下边的代码说明了如何在MIDlet中将字符数组数据读取和写入到RMS的RecortStore中,每个RecordStore包括id,长度和数组数据
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class arrayStore extends MIDlet
{
private RecordStore rs = null;
static final String RECORD_STORE = "rmstest";
public arrayStore()
{
open();
writeData();
readData();
close();
delete();
}
public void destroyApp( boolean unconditional )
{}
public void startApp()
{
destroyApp(false);
notifyDestroyed();
}
public void pauseApp(){}
/* 打开RecordStore */
public void open()
{
try
{
rs = RecordStore.openRecordStore(RECORD_STORE, true );
}
catch (Exception e)
{}
}
/* 关闭RecordStore*/
public void close()
{
try
{
rs.closeRecordStore();
}
catch (Exception e)
{}
}
/* 删除RecordStore*/
public void delete()
{
if (RecordStore.listRecordStores() != null)
{
try
{
RecordStore.deleteRecordStore(RECORD_STORE);
}
catch (Exception e)
{}
}
}
/* 写入数据*/
public void writeData()
{
int ids[] = {1,2,3};
String str1[] = {"A", "B", "C"};
String str2[] = {"D", "E", "F"};
String str3[] = {"G", "H", "I"};
Object data[] = new Object[3];
data[0] =str1;
data[1]= str2;
data[2]= str3;
writeStream(ids,data);
}
/* 写入数据到RMS */
public void writeStream(int[] ids,Object[] data)
{
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream ds = new DataOutputStream(baos);
byte[] record;
for (int i = 0; i < ids.length; i++)
{
ds.writeInt(ids[i]); // 写入id
String str[] = (String[])data[i];
ds.writeInt(str.length); // 写入数据长度
for (int j=0;j<str.length;j++)
{
ds.writeUTF(str[j]); // 写入数组数据
}
ds.flush();
record = baos.toByteArray();
// 添加数据到RecordStore
rs.addRecord(record, 0, record.length);
baos.reset();
}
baos.close();
ds.close();
}
catch (Exception e)
{}
}
/* 从RecordStore中读取数据*/
public void readData()
{
try
{
byte[] recData = new byte[50];
ByteArrayInputStream bais = new ByteArrayInputStream(recData);
DataInputStream ds = new DataInputStream(bais);
for (int i = 1; i <= rs.getNumRecords(); i++)
{
// Get data into the byte array
rs.getRecord(i, recData, 0);
System.out.println("Record #" + i);
System.out.println("ID: " + ds.readInt());
int length = ds.readInt();
System.out.println("Length: " + length);
for(int j =0 ;j<length;j++)
{
System.out.println("Data: " +ds.readUTF());
}
System.out.println("--------------------");
bais.reset();
}
bais.close();
ds.close();
}
catch (Exception e)
{}
}
}