一、什么是序列化: 序列化理解成“打碎”是可以的,不過在書本上的名詞就是將對象轉換成二進制。
二、在java中如何實現序列化: 首先我們要把准備要序列化類,實現 Serializabel接口 例如:我們要Person類里的name和age都序列化
import java.io.Serializable; public class Person implements Serializable { //本類可以序列化 private String name ; private int age ; public Person(String name,int age) { this.name = name ; this.age = age ; } public String toString() { return "姓名:" + this.name + ",年齡" + this.age ; } }
然后:我們將name和age序列化(也就是把這2個對象轉為二進制,統族理解為“打碎”)
package org.lxh.SerDemo; import java.io.File; import java.io.FileOutputStream; import java.io.ObjectOutputStream ; public class ObjectOutputStreamDemo { //序列化 public static void main(String[] args) throws Exception { //序列化后生成指定文件路徑 File file = new File("D:" + File.separator + "person.ser") ; ObjectOutputStream oos = null ; //裝飾流(流) oos = new ObjectOutputStream(new FileOutputStream(file)) ; //實例化類 Person per = new Person("張三",30) ; oos.writeObject(per) ; //把類對象序列化 oos.close() ; } }
序列化是將對象狀態轉換為可保持或傳輸的格式的過程。說明白點就是你可以用對象輸出流輸出到文件.如果不序列化輸出的話.很可能會亂!
實現方式是實現java.io.Serializable接口.這個接口不需要實現任何具體方法.只要implements java.io.Serializable 就好了