public class MyByteArrayOutputStream extends ByteArrayOutputStream{ public byte[] getByteArray() {return buf; } }
在J2ME中并没有提供对象序列化的机制,但是我们可以自己实现它。请考虑下面这个类:
public class Bank{ private String bankName; private String phone; private int employeeNum; public Bank(){} public Bank(String aBankName, String aPhone,int aEmployeeNum) { this.bankName = aBankName; this.phone = aPhone; this.employeeNum = aEmployeeNum; } public String getBankName() { return bankName !=null?bankName:""; } public String getPhone() { return phone!=null?phone:""; } public int getEmployeeNum() { return employeeNum; }}
我们添加两个方法到这个类来实现对象序列化。如下所示:
public class Bank{ private String bankName; private String phone; private int employeeNum; public Bank(){} public Bank(String aBankName, String aPhone,int aEmployeeNum) { this.bankName = aBankName; this.phone = aPhone; this.employeeNum = aEmployeeNum; } public String getBankName() { return bankName !=null?bankName:""; } public String getPhone() { return phone!=null?phone:""; } public int getEmployeeNum() { return employeeNum; } public byte[] serialize() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos);dos.writeUTF(getBankName()); dos.writeUTF(getPhone()); dos.writeInt(getEmployeeNum()); dos.flush();return bos.toByteArray(); } public Bank deserialize (byte[] data) throws IOException { ByteArrayInputStream bis = new ByteArrayInputStream(data); DataInputStream dis = new DataInputStream(bis);Bank myBank = new Bank(); myBank.bankName = dis.readUTF(); myBank.phone = dis.readUTF(); myBank.employeeNum = dis.readInt();return myBank; }}
这样我们就实现了对象的序列化,使用起来也非常简单。序列化和反序列化的操作分别如下面所示:
Bank aBank = .....;RecordStore rs = .....;try{ byte[] data = aBank.serialize(); rs.addRecord(data,0,data.length); }catch(IOException e){ //do something }catch(RecordStoreException e){ //do something }????????????????????????????byte[] data = ..........;Bank aBank = null;try{ aBank = Bank.deserialize(data); }catch(IOException e){ }
值得注意的一点是在Bank类中我们的成员都是基本数据类型以及String类型,并不存在指向其他对象的引用,这是最理想也是最简单的情况,事实上我们在J2ME中设计序列化的类的时候也应该尽量这样做,避免不必要得麻烦。
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com/bianchengyuyan/)