JAVA序列化和反序列化
序列化的目的:1、将对象保存到磁盘上。2、允许在网络中传输对象。
无论是通过磁盘还是通过网络都可以把序列化的二进制流恢复成原来的java对象。
要让某个对象可序列化就要实现接口Serializable或者Externalizable
如果是Externalizable接口需要实现下面两个方法
@Override public void writeExternal(ObjectOutput out) throws IOException { } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { }
一般我们实现Serializable接口并通过对象流实现序列化
序列化和反序列化简单测试代码:
public class Book implements Externalizable { /** * 序列化版本作用:1.项目升级时,class文件也会升级,保证兼容性,使对象能正确被反序列化。 * 2.有利于程序在不同的JVM之间移植 */ private static final long serialVersionUID = 2629435315068538625L; /** * 书名 */ private String name; /** * 作者 */ private String author; /** * 页数 */ private int page; /** * 初始价格 * transient 隔离序列化机制 */ private transient int price; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public void writeExternal(ObjectOutput out) throws IOException { } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } }
public class SerializableBook { public static void main(String[] args) { //序列化,java7 支持try(){}方式自动关闭资源文件,无需finally中关闭 try (ObjectOutputStream objectOutputStream = new ObjectOutputStream( new FileOutputStream("F:\\SerializableBook.txt"))) { Book book = new Book(); book.setName("三国演义"); book.setAuthor("阿汤哥"); book.setPage(100); book.setPrice(20); //writeObject()将对象输出到输出流中 objectOutputStream.writeObject(book); //改变后的值不会被输出,只输出第一次序列化的值 book.setName("西游记"); objectOutputStream.writeObject(book); } catch (IOException e) { e.printStackTrace(); } //反序列化 try (ObjectInputStream objectInputStream = new ObjectInputStream( new FileInputStream("F:\\SerializableBook.txt"))) { //readObject()从输入流中读取 Book getBook = (Book) objectInputStream.readObject(); System.out.println(getBook.getName() + getBook.getAuthor() + getBook.getPage()); //transient 隔离序列化机制,所以输出是0 System.out.println(getBook.getPrice()); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }