使用对象流实现序列化

来源:互联网 发布:信托网络个人理财产品 编辑:程序博客网 时间:2024/04/30 18:36

如果需要将某个对象保存在磁盘上或是通过网络传输,那么这个类应该实现Serializable

其实实现Serializable非常简单,只要让目标类实现Serializable接口即可,也无需实现任何的方法。下面是通过对象流实现序列化的一个列子:

package Test;import java.io.ObjectOutputStream;import java.io.FileOutputStream;public class WriteObj {public static void main(String[] args){ObjectOutputStream oos=null;try{//下面三行就是对象实现序列化并输出到文件中的一般操作oos=new ObjectOutputStream(new FileOutputStream("object.txt"));Person ps=new Person("qianhao",18);//将对象输出到输出流,放到了object.txt文件oos.writeObject(ps);}catch(Exception e){e.printStackTrace();}finally{try{if(oos!=null){oos.close();}}catch(Exception e1){e1.printStackTrace();}}}}

下面是反序列化的列子:

package Test;import java.io.ObjectInputStream;import java.io.FileInputStream;public class ReadObj {public static void main(String[] args){ObjectInputStream ois=null;try{ois=new ObjectInputStream(new FileInputStream("object.txt"));Person p=(Person)ois.readObject();System.out.println("name is"+p.getName()+"age is"+p.getAge());}catch(Exception e){e.printStackTrace();}finally{try{if(ois!=null){ois.close();}}catch(Exception e1){e1.printStackTrace();}}}}


在反序列化程序中出现以下问题:

java.io.InvalidClassException: Test.Person; local class incompatible: stream classdesc serialVersionUID = 6617217288378285778, local class serialVersionUID = -2190347773987930449
 at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
 at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
 at java.io.ObjectInputStream.readClassDesc(Unknown Source)
 at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
 at java.io.ObjectInputStream.readObject0(Unknown Source)
 at java.io.ObjectInputStream.readObject(Unknown Source)

大概意思就是serialVersionUID不相匹配,所以需要在Person类中加上private  long serialVersionUID=6617217288378285778l;



0 0
原创粉丝点击