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

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;
}
}
}

你可能感兴趣的:(常用工具类)