序列化基本概念
定義:將內存中保存的對象變爲二進制數據流的形式進行傳輸或保存在文本中。
實現:Java中類若要被序列化輸出,該類必須實現Serializable
接口。該接口是一個標識接口,表示該類具有序列化的功能。
public interface Serializable {
}
序列化與反序列化操作
要想實現序列化與反序列化的對象操作,需要使用io包提供的兩個類ObjectOutputStream
、ObjectInputStream
範例:實現對象序列化
import java.io.*;
class Person implements Serializable{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class TestFileStream {
public static void main(String[] args) throws Exception{
File file = new File("C:" + File.separator + "Users" + File.separator
+ "DELL" + File.separator + "Desktop" + File.separator + "Test.txt");
Person person = new Person("改革開放",40);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(person);
oos.close();
}
}
範例:實現對象反序列化
import java.io.*;
class Person implements Serializable{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class TestFileStream {
public static void main(String[] args) throws Exception{
File file = new File("C:" + File.separator + "Users" + File.separator
+ "DELL" + File.separator + "Desktop" + File.separator + "Test.txt");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Object result = ois.readObject();
System.out.println(result);
ois.close();
}
}
transient關鍵字
使用Serializable
序列化輸出時,默認將對象的所有屬性以及值均序列化以及反序列化。如果希望某些屬性值不進行序列化輸出,可以在屬性前加transient
關鍵字
import java.io.*;
class Person implements Serializable{
private String name;
private transient int age; // 加上transient關鍵字
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class TestFileStream {
public static void main(String[] args) throws Exception{
File file = new File("C:" + File.separator + "Users" + File.separator
+ "DELL" + File.separator + "Desktop" + File.separator + "Test.txt");
Person person = new Person("改革開放",40);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(person);
oos.close();
File file1 = new File("C:" + File.separator + "Users" + File.separator
+ "DELL" + File.separator + "Desktop" + File.separator + "Test.txt");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file1));
Object result = ois.readObject();
System.out.println(result);
ois.close();
}
}
運行結果:
Person{name='改革開放', age=0}