集合是存放对象的类,要想计算出集合中的字节数,必须要将存放在集合中的对象实现一个方法:
这里类的成员变量以及它们的setter and getter就不提供了
public void serialize(DataOutputStream dataStream)
throws ApplicationException{
try{
dataStream.writeUTF(getJXFS()) ;
dataStream.writeUTF(getZBXZ());
dataStream.writeUTF(getCQ());
dataStream.writeUTF(getCJ());
dataStream.writeUTF(getKHMC());
dataStream.writeUTF(getCCBH());
dataStream.writeUTF(getBHLX());
dataStream.writeLong(MPRL==null? 0:MPRL.longValue());
dataStream.writeUTF(getXH());
dataStream.writeUTF(getJXZB());
dataStream.writeUTF(getCCRQ());
dataStream.writeUTF(getXLMC());
dataStream.writeUTF(getTYRQ());
dataStream.writeUTF(getBH());
dataStream.writeUTF(getLQFS());
dataStream.writeUTF(getAZRQ());
dataStream.writeUTF(getKHBH());
dataStream.writeUTF(getMC());
dataStream.writeLong(RL==null? 0:RL.longValue());
dataStream.flush();
}catch(IOException e){
throw new ApplicationException(e);
}
}
public static UeiByq deserialize(DataInputStream dataStream)
throws ApplicationException{
try{
UeiByq entity = new UeiByq();
entity.JXFS = dataStream.readUTF() ;
entity.ZBXZ = dataStream.readUTF();
entity.CQ = dataStream.readUTF();
entity.CJ = dataStream.readUTF();
entity.KHMC = dataStream.readUTF();
entity.CCBH = dataStream.readUTF();
entity.BHLX = dataStream.readUTF();
entity.MPRL = new Long(dataStream.readLong());
entity.XH = dataStream.readUTF();
entity.JXZB = dataStream.readUTF();
entity.CCRQ = dataStream.readUTF();
entity.XLMC = dataStream.readUTF();
entity.TYRQ = dataStream.readUTF();
entity.BH = dataStream.readUTF();
entity.LQFS = dataStream.readUTF();
entity.AZRQ = dataStream.readUTF();
entity.KHBH = dataStream.readUTF();
entity.MC = dataStream.readUTF();
entity.RL = new Long(dataStream.readLong());
return entity;
}catch(IOException e){
throw new ApplicationException(e);
}
}
即实现序列化和反序列化,要注意的是序列化的时候,属性是什么顺序,反序列化的时候属性就是什么顺序,还要注意的是:DataOutputStream是一个字符流,所以它包装类字节流,一般字符流是有缓冲区的(byte[]),对象的序列化,反序列化肯定是要占用缓冲区的,因此缓冲区要定义一个合适的大小;
需要注意的是:序列化的时候,调用dataStream.writeUTF(getKHBH());的时候一定要保证属性KHBH(字符串类型的)不能为空,所以在get的时候要处理null的情况,处理如下:
Public String getKHBH(){return this.KHBH==null?””:this.KHBH.trim()}
包装类型的属性的判空操作直接在流输出的时候进行处理,见上面的serialize方法。
这样集合所包含的总字节数就可以通过循环来累加了
(一个对象的字节数:dataStream.size())
思路二:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(Object obj);
int size = bos.toByeArray().length;//对象的字节长度,注意输出流的缓存是动态变化的,我测试的好像是几百万字节,超过一千万就内存溢出了