序列化是將對象的狀態信息轉換爲能夠存儲或傳輸的形式的過程,在序列化期間,對象將其帶你過去的狀態寫入到臨時或持儲存區,反序列化就是從新建立對象的過程,此對象來自於臨時或持久儲存區。java
就比如如存儲數據到數據庫,將一些數據持久化到數據庫中,而有時候須要將對象持久化,雖說將對象狀態持久化的方式有不少,可是java給咱們提供了一種很便捷的方式,那就是序列化,序列化能夠實現對象到文件之間的直接轉換,實現細節對咱們隱藏。數據庫
具體的三種用途:數組
實現Serializable接口,經過ObjectOutputStream和ObjectInputStream將對象序列化和反序列化。網絡
import java.io.*; public class User implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } public static void main(String[] args) throws IOException, ClassNotFoundException { // User user = new User("gol",22); // ByteArrayOutputStream bo = new ByteArrayOutputStream(); // ObjectOutputStream oo = new ObjectOutputStream(bo); // oo.writeObject(user);//序列化.user寫入字節數組流中 // ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); // ObjectInputStream oi = new ObjectInputStream(bi); // User userSer = (User) oi.readObject();//反序列化 // System.out.println(userSer); User user = new User("gol",22); FileOutputStream fos = new FileOutputStream("a.txt"); ObjectOutputStream oo = new ObjectOutputStream(fos); oo.writeObject(user);//序列化.user寫入文件中 FileInputStream fis = new FileInputStream("a.txt"); ObjectInputStream oi = new ObjectInputStream(fis); User userSer = (User) oi.readObject();//反序列化 System.out.println(userSer); oi.close(); fis.close(); oo.close(); fos.close(); } }
Externalizable接口繼承了Serializable接口,替咱們封裝了兩個方法,一個用於序列化,一個用於反序列化。這種方式是將屬性序列化,注意這種方式transient修飾詞將失去做用,也就是說被transient修飾的屬性,只要你在writeExternal方法中序列化了該屬性,照樣也會獲得序列化。ide
import java.io.*; public class User implements Externalizable { private static final long serialVersionUID = 1L; private String name; private int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(this.name);//將屬性分別序列化 out.writeObject(this.age); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.name=(String)in.readObject();//反序列化屬性 this.age=(int)in.readObject(); } public static void main(String[] args) throws IOException, ClassNotFoundException { FileOutputStream fos = new FileOutputStream("a.txt"); ObjectOutputStream oo = new ObjectOutputStream(fos); FileInputStream fis = new FileInputStream("a.txt"); ObjectInputStream oi = new ObjectInputStream(fis); User user = new User("gol",19); user.writeExternal(oo);//序列化 User userEnr = new User(); userEnr.readExternal(oi);//反序列化 System.out.println(userEnr); oi.close(); fis.close(); oo.close(); fos.close(); } }
注意如下三點:this