认识一下Java序列化
package com.cxyapi.io;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;/** 认识一下Java序列化 * @author cxy @ www.cxyapi.com */public class SerializableTest{public static void main(String[] args) throws Exception{//演示一:最简单的序列化例子ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("d:/cxyapi.data"));Book b1=new Book("Java教程");oos.writeObject(b1);oos.close();ObjectInputStream ois=new ObjectInputStream(new FileInputStream("d:/cxyapi.data"));Book b2=(Book)ois.readObject();System.out.println(b2.getName());ois.close();System.out.println("=====================");//演示二:一个包含其他对象的对象oos=new ObjectOutputStream(new FileOutputStream("d:/cxyapi.data"));Author a=new Author("cxy");//点1:两本书我存同一个对象(作者)BookExt be=new BookExt("cxyapi", a);BookExt be1=new BookExt("snkcxy.iteye.com", a);oos.writeObject(be);//点2:我存2遍be1oos.writeObject(be1);oos.writeObject(be1);oos.close();ois=new ObjectInputStream(new FileInputStream("d:/cxyapi.data"));//存3个对象 我取3个对象,多取会报错BookExt bec=(BookExt)ois.readObject();BookExt be1c=(BookExt)ois.readObject();BookExt be1cc=(BookExt)ois.readObject();System.out.println(bec.getName());System.out.println(be1c.getName());System.out.println(be1cc.getName());//判断最后2个对象 其实是一个对象,这是Java序列化机制所知,它不会一下序列化出很多同样的对象System.out.println(be1c==be1cc);System.out.println(be1c.hashCode());System.out.println(be1cc.hashCode());//判断作者,其实也是同一个对象System.out.println(bec.getAuthor()==be1c.getAuthor());System.out.println(bec.getAuthor().hashCode());System.out.println(be1c.getAuthor().hashCode());ois.close();System.out.println("=====================");}}class Book implements Serializable{private static final long serialVersionUID = -564380176443249810L;private String name;public Book(String name){this.name=name;}public String getName(){return name;}public void setName(String name){this.name = name;}}/** 扩展书类,实现序列化 并且里面加入了作者信息 * @author cxy @ www.cxyapi.com * 2013-3-12 下午11:18:22 */class BookExt implements Serializable{private String name;private Author author;public BookExt(String name,Author author){this.name=name;this.author=author;}public String getName(){return name;}public void setName(String name){this.name = name;}public Author getAuthor(){return author;}public void setAuthor(Author author){this.author = author;}}/** 必须能序列化 不然 BookExt也将不能序列化 * @author cxy @ www.cxyapi.com * 2013-3-12 下午11:42:40 */class Author implements Serializable{private String name;public Author(String name){this.name=name;}public String getName(){return name;}public void setName(String name){this.name = name;}}
?
声明:
1.原创文章,转载请标明并加本文连接。
2.文章反映个人愚见,如有异议欢迎讨论指正
3.更多的内容请看我的 ?个人博客(测试版)