对象和数组相互转换的方法实例

package prj15test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;


public class SaveObjectToRMS extends MIDlet {

public SaveObjectToRMS() {
}

protected void startApp() throws MIDletStateChangeException {
RecordStore rs=null ;
try{
rs = RecordStore.openRecordStore("RS2", true);
Customer cus = new Customer();
cus.setCname("八尺琼");
cus.setPhone("1376***3450");
cus.setAge(22);
//转换为字节数组写入记录
byte[] b1 = cus.objectToByteArray();
rs.addRecord(b1, 0, b1.length);
//(字节数字转换为对象)读取记录
byte[] b2 = rs.getRecord(1);
Customer cus1 = Customer.byteArrayToObject(b2);
System.out.println(cus1.getCname());
System.out.println(cus1.getPhone());
System.out.println(cus1.getAge());
}catch(Exception e){
e.printStackTrace();
}
finally{
try {
rs.closeRecordStore();
} catch (RecordStoreNotOpenException e) {
e.printStackTrace();
} catch (RecordStoreException e) {
e.printStackTrace();
}
}

}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {

}

protected void pauseApp() {

}

static class Customer{
private String cname;
private String phone;
private int age;
//将对象转化为数组
public byte[] objectToByteArray() throws Exception{
ByteArrayOutputStream baos = new  ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
//用dos将对象内容写入baos
dos.writeUTF(this.cname);
dos.writeUTF(this.phone);
dos.writeInt(this.age);
baos.close();
dos.close();
return baos.toByteArray();  //返回字节数组
}
//将字节数组转化为对象
public static Customer byteArrayToObject(byte[] b) throws Exception{
ByteArrayInputStream bais = new  ByteArrayInputStream(b);
DataInputStream dis = new DataInputStream(bais);
//从bais中读取内容
Customer cus = new Customer();
cus.setCname(dis.readUTF());
cus.setPhone(dis.readUTF());
cus.setAge(dis.readInt());
bais.close();
dis.close();
return cus;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值