简单封装MIDP RMS操作

王朝other·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

许多MIDP应用程序需要简单的存储配置信息,对此,简单封装一个RMSHandler,实现一条记录的读写:

package com.crackj2ee.midp.rms;

import Java.io.*;

import javax.microedition.rms.*;

public final class RMSHandler {

private static final String RECORD_STORE_NAME = "RmsDaTa";

public static boolean loadUniqueRecord(Persistentable p) {

byte[] data = loadUniqueRecord();

if(data==null)

return false;

DataInputStream input = null;

try {

input = new DataInputStream(new ByteArrayInputStream(data));

p.load(input);

return true;

}

catch(IOException ioe) {

return false;

}

finally {

try {

input.close();

}

catch (Exception e) {}

}

}

public static boolean saveUniqueRecord(Persistentable p) {

DataOutputStream output = null;

try {

ByteArrayOutputStream bytes = new ByteArrayOutputStream();

output = new DataOutputStream(bytes);

p.save(output);

return saveUniqueRecord(bytes.toByteArray());

}

catch(IOException ioe) {

return false;

}

finally {

if(output!=null)

try {

output.close();

}

catch (Exception e) {}

}

}

private static byte[] loadUniqueRecord() {

RecordStore rs = null;

RecordEnumeration re = null;

try {

rs = RecordStore.openRecordStore(RECORD_STORE_NAME, true);

if(rs.getNumRecords()==0)

return null;

re = rs.enumerateRecords(null, null, false);

if(re.hasNextElement())

return re.nextRecord();

return null;

}

catch(RecordStoreException rse) {

return null;

}

finally {

if(re!=null) {

re.destroy();

}

if(rs!=null) {

try {

rs.closeRecordStore();

}

catch (Exception e) {}

}

}

}

private static boolean saveUniqueRecord(byte[] data) {

RecordStore rs = null;

RecordEnumeration re = null;

try {

rs = RecordStore.openRecordStore(RECORD_STORE_NAME, true);

re = rs.enumerateRecords(null, null, false);

if(re.hasNextElement()) {

rs.setRecord(re.nextRecordId(), data, 0, data.length);

}

else {

rs.addRecord(data, 0, data.length);

}

return true;

}

catch(RecordStoreException rse) {

return false;

}

finally {

if(re!=null) {

re.destroy();

}

if(rs!=null) {

try {

rs.closeRecordStore();

}

catch (Exception e) {}

}

}

}

}

需要持久化的类实现一个Persistentable接口:

package com.crackj2ee.midp.rms;

import java.io.*;

public interface Persistentable {

void save(DataOutputStream output) throws IOException;

void load(DataInputStream input) throws IOException;

}

读写数据时,按照顺序依次读写即可,例如:

class MyForm extends Form implements Persistentable {

private int score;

private String username;

public MyForm() {

super("Test");

load(this);

}

public void save(DataOutputStream output) throws IOException {

output.writeInt(score);

output.writeUTF8(username);

}

public void load(DataInputStream input) throws IOException {

score = input.readInt();

username = input.readUTF8();

}

}

(出处:http://www.knowsky.com)

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航