简单的序列化测试

public class TestSereialization implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -4108224186821624775L;
	
	private String str;	

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}

	public static void main(String[] args) throws Exception {
		
		TestSereialization ts = new TestSereialization();
		ts.setStr("cathy is very pretty.");
		
		FileOutputStream fos = new FileOutputStream(new File("E:/test.txt"));
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(ts);
		oos.close();
		
		FileInputStream fis = new FileInputStream(new File("E:/test.txt"));
		ObjectInputStream ois = new ObjectInputStream(fis);
		TestSereialization ts2 = (TestSereialization)ois.readObject();
		ois.close();
		System.out.println(ts2.getStr());
	}
}

结果输出为

我们可以看看E:\\test.txt的内容。


接下来我们更改一下serialVersionUID,然后再直接反序列化会怎样呢

public class TestSereialization implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -5L;
	
	private String str;	

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}

	public static void main(String[] args) throws Exception {
		
		TestSereialization ts = new TestSereialization();
		ts.setStr("cathy is very pretty.");
		/*
		FileOutputStream fos = new FileOutputStream(new File("E:/test.txt"));
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(ts);
		oos.close();*/
		
		FileInputStream fis = new FileInputStream(new File("E:/test.txt"));
		ObjectInputStream ois = new ObjectInputStream(fis);
		TestSereialization ts2 = (TestSereialization)ois.readObject();
		ois.close();
		System.out.println(ts2.getStr());
	}
}
一下是console的报错显示:
local class incompatible: stream classdesc serialVersionUID = -4108224186821624775, local class serialVersionUID = -5

阅读更多
文章标签: 序列化
个人分类: java基础
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭