定義:
串行化(Serialization)是计算机科学中的一个概念,它是指将对象存储到介质(如文件、内存缓冲区等)中或是以二进制方式通过网络传输。
Java實現:
1. 對象其類必須實現Serializable接口。
2. 保存的數據為:普通成員變量值。(注:靜態成員變量,類方法,以及transient修飾的變量,全部忽略不保存。)
3. 由對象輸入/輸出流來實現。
例子:
串行化(序列化)類
package com.my.ser;
import java.io.Serializable;
/**
* @author Jack 2014-10-29 上午09:27:06
*
*/
public class Car implements Serializable{
public static String xingHao = "WPL";
public transient int post = 123;
public String name;
public void start() {
System.out.println("啟動汽車");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "XingHao: "+this.xingHao + ",post: "+this.post+",name: "+this.name;
}
}
測試類
package com.my.ser;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* @author Jack 2014-10-29 上午09:29:29
*
*/
public class CarSer {
public static void main(String[] args) {
Car car = new Car();
car.setName("JackCar");
String filePath = "CarDemo.out";
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(filePath);
oos = new ObjectOutputStream(fos);
oos.writeObject(car);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos == null) fos.close();
if (oos == null) oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Car newCar = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(filePath);
ois = new ObjectInputStream(fis);
newCar = (Car)ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis == null) fis.close();
if (ois == null) ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("OldCar: " + car + "\nNewCar: " + newCar);
}
}
運行結果
OldCar: XingHao: WPL,post: 123,name: JackCar
NewCar: XingHao: WPL,post: 0,name: JackCar