13,100
社区成员
发帖
与我相关
我的任务
分享
public class MIDlet4 extends MIDlet {
protected void startApp() throws MIDletStateChangeException {
RecordStore rs = null;
try{
rs = RecordStore.openRecordStore("RS1", true);
Customer cus = new Customer();
cus.setCname("王强");
cus.setPhone("02567823456");
cus.setAge(34);
//转换为字节数组写入
byte[] b1 = cus.object2ByteArray();
rs.addRecord(b1, 0, b1.length);
//读
byte[] b2 = rs.getRecord(1);
Customer newCus = Customer.byteArray2Object(b2);
System.out.println(newCus.getCname());
System.out.println(newCus.getAge());
}catch(Exception ex){
ex.printStackTrace();
}
finally{
try{
rs.closeRecordStore();
}catch(Exception ex){}
}
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
}
class Customer{
private String cname;
private String phone;
private int age;
//将对象转为字节数组
public byte[] object2ByteArray() 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 byteArray2Object(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;
}
}