前言:有沒有想過,如何將對象進行“加密”後寫入磁盤?序列化幫你實現!
1.概念
序列化 (Serialization)將對象的狀態信息轉換為可以存儲或傳輸的形式的過程。在序列化期間,對象將其當前狀態寫入到臨時或持久性存儲區。以後,可以通過從存儲區中讀取或反序列化對象的狀態,重新創建該對象.
2.反序列化Java實驗
--測試的實體類--
package exercise;
import java.io.Serializable;
public class Person implements Serializable{
private String name;
private int age;
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
1)單對象序列化
package exercise;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class ObjectStreamDemo1 {
/**
* @param args
* @throws IOException
* @throws ClassNotFoundException
*/
public final static String PATH = "obj.object1";
public static void main(String[] args) throws IOException,
ClassNotFoundException {
//writeObj();
readObj();
System.out.println("--End--");
}
public static void readObj() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
PATH));
Person p = (Person)ois.readObject();
System.out.println(p.getName() + "|" + p.getAge());
}
public static void writeObj() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
PATH));
oos.writeObject(new Person("張三", 30));
oos.close();
}
}
結果顯示
2)多對象序列化
package exercise;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class ObjectStreamDemo2 {
/**
* @param args
* @throws IOException
* @throws ClassNotFoundException
*/
public final static String PATH = "obj.object";
public static void main(String[] args) throws IOException,
ClassNotFoundException {
//writeObj();
readObj();
System.out.println("---end!---");
}
public static void readObj() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
PATH));
List<Person> persons = (List<Person>)ois.readObject();
for(Person p:persons){
System.out.println(p.getName() + "|" + p.getAge());
}
}
public static void writeObj() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
PATH));
List<Person> persons = new ArrayList<Person>();
Person p1 = new Person("張三",18);
Person p2 = new Person("李四",19);
persons.add(p1);
persons.add(p2);
oos.writeObject(persons);
oos.close();
}
}
結果顯示
注意:
·實體類必須實現序列化接口“java.io.Serializable”
·生成的obj.object 因為是二進制文件,故無法正常打開,若notepad打開也是亂碼!
總結:序列化技術在web端技術的應用相當重要,希望學習Java的朋友都能理解該技術並進行應用。
以上內容純屬個人學習總結,不代表任何團體或單位。若有理解不到之處請見諒!