package com.RMS; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; import javax.microedition.rms.RecordStore; public class RecordStoreTest extends MIDlet { protected void destroyApp(boolean arg0) throws MIDletStateChangeException { } protected void pauseApp() { } protected void startApp() throws MIDletStateChangeException { RecordStore rs = null; try { rs = RecordStore.openRecordStore("RS1", true); Customer cus = new Customer(); cus.setName("张三"); cus.setPhone("123456"); cus.setAge(19); //写 byte[] b1 = cus.ObjToByte(); rs.addRecord(b1, 0, b1.length); //读 byte[] b2 = rs.getRecord(1); Customer newCus = Customer.ByteToObj(b2); System.out.println(newCus.getName()+" "+newCus.getAge()+" "+newCus.getPhone()); } catch (Exception e) { e.printStackTrace(); } finally { try { rs.closeRecordStore(); } catch (Exception e) { e.printStackTrace(); } } } } class Customer { private String name; private int age; private String phone; //将对象转为字节数组 public byte[] ObjToByte() throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeUTF(this.name); dos.writeUTF(this.phone); dos.writeInt(this.age); baos.close(); dos.close(); return baos.toByteArray(); } //将字节数组转为对象 public static Customer ByteToObj(byte[] b) throws IOException{ ByteArrayInputStream bais = new ByteArrayInputStream(b); DataInputStream dis = new DataInputStream(bais); Customer cus = new Customer(); cus.setName(dis.readUTF()); cus.setPhone(dis.readUTF()); cus.setAge(dis.readInt()); bais.close(); dis.close(); return cus; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }