扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
许多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();
}
}
查看本文来源
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者