1、什么是序列化与反序列化?
序列化是指将Java对象通过字节流或者文件(XML)的形式持久化到文件或者数据库的过程。反序列化则是次序列化的Java对象反向恢复成对象的过程。
2、为什么要实现序列化与反序列化?
我们知道,当两个进程进行远程通信时,可以相互发送各种类型的数据,包括文本、图片、音频、视频等, 而这些数据都会以二进制序列的形式在网络上传送。那么当两个Java进程进行通信时,能否实现进程间的对象传送呢?答案是可以的。如何做到呢?这就需要Java序列化与反序列化了。换句话说,一方面,发送方需要把这个Java对象转换为字节序列,然后在网络上传送;另一方面,接收方需要从字节序列中恢复出Java对象。
当我们明晰了为什么需要Java序列化和反序列化后,我们很自然地会想Java序列化的好处。其好处一是实现了数据的持久化,通过序列化可以把数据永久地保存到硬盘上(通常存放在文件里),二是,利用序列化实现远程通信,即在网络上传送对象的字节序列。(以上内容来自网络)
3、如何实现序列化与反序列化?
3.1Java中实现序列化和反序列化
Java中实现序列化与反序列化是通过实现 Serializable 接口标志一个对象可以被序列化与反序列化,在程序中序列化通过 new ObjectOutPutStream(new FileOutPutStream(new File(path))).writeObject()实现对一个对象的序列化, new ObjectInPutStream(new FileInPutStream(new File(path))).readObject()实现对一个对象的反序列化读取。具体代码如下:
序列化对象Person:
package com.serialize.leiht; import java.io.Serializable; public class Person implements Serializable { private String name; private String telPhone; private int id; private String sex; public Person(String name, String telPhone, int id, String sex) { super(); this.name = name; this.telPhone = telPhone; this.id = id; this.sex = sex; } @Override public String toString() { return this.name + this.telPhone + this.id + this.sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTelPhone() { return telPhone; } public void setTelPhone(String telPhone) { this.telPhone = telPhone; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
序列化对象过程(WriteObject)
package com.serialize.leiht; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class WritePerson { public static void main(String[] args) { FileOutputStream fos = null; ObjectOutputStream oos = null; try { String path = "src/person.bin"; fos = new FileOutputStream(new File(path)); oos = new ObjectOutputStream(fos); Person p = new Person("zhangsan", "13880246907", 100, "man"); oos.writeObject(p); System.out.println("序列化Person成功!"); }catch(Exception e) { e.printStackTrace(); }finally { if(oos != null) { try { oos.close(); } catch (IOException e) { e.printStackTrace(); } } if(fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
反序列化过程(ReadObject)
package com.serialize.leiht; import java.io.File; import java.io.FileInputStream; import java.io.ObjectInputStream; public class ReadPerson { public static void main(String[] args) { FileInputStream fis = null; ObjectInputStream ois = null; try { String path = "src/person.bin"; fis = new FileInputStream(new File(path)); ois = new ObjectInputStream(fis); Person person = (Person) ois.readObject(); if(person == null) { System.out.println("反序列货失败!"); }else { System.out.println(person); } }catch(Exception e) { e.printStackTrace(); }finally{ } } }