Java序列化与反序列化(Serializable)

来源:互联网 发布:定位软件哪个好 编辑:程序博客网 时间:2024/05/01 14:16

Java序列化与反序列化(Serializable)

特别注意:

1.要序列化的类必须实现Serializable借口

2.在反序列化(读取对象)的时候必须额外捕获EOFException

3.序列化之后的文件是“乱码”

 

 

package com.frank.io;import java.io.EOFException;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;/**   * author:pengyan    * date:Jun 15, 2011    * file:ObjectInputOutputStreamTest.java   */ public class ObjectInputOutputStreamTest {String path="E:\\planda.p";public static void main(String[] args) throws Exception {ObjectInputOutputStreamTest test=new ObjectInputOutputStreamTest();test.outputObject();test.inputObject();}private void inputObject() throws Exception {//create inputObjectStreamObjectInputStream ois=new ObjectInputStream(new FileInputStream(path));// temp object to receive the value of this stream read everytimeObject obj=null;PandaEntity p=null;try {while((obj=ois.readObject())!=null){p=(PandaEntity)obj;//show the object read by the streamSystem.out.println(p.toString());}} catch (EOFException e) {//throw EOFException when read endSystem.err.println("读取完毕");}}private void outputObject() throws Exception{//create two object to outputPandaEntity p1=new PandaEntity(1000,"团团",3);PandaEntity p2=new PandaEntity(2000,"圆圆",3);//create the output streamObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(path));//write objectoos.writeObject(p1);oos.writeObject(p2);//flush the streamoos.flush();//close the streamoos.close();}}class PandaEntity implements Serializable{/*the class must implements Serializable interface * or there will throw java.io.NotSerializableException  * */private Integer id;private String name;private Integer age;@Overridepublic String toString() {return "id:"+id+"\tname:"+name+"\tage:"+age;}public PandaEntity() {}public PandaEntity(Integer id, String name, Integer age) {this.id = id;this.name = name;this.age = age;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}}

 

0 0
原创粉丝点击