使用对象流实现序列化

如果需要将某个对象保存在磁盘上或是通过网络传输,那么这个类应该实现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;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值