Java序列化與反序列化【例項】
阿新 • • 發佈:2019-01-04
基本概念:
序列化是將物件狀態轉換為可保持或傳輸的格式的過程。與序列化相對的是反序列化,它將流轉換為物件。這兩個過程結合起來,可以輕鬆地儲存和傳輸資料。
序列化為一般檔案,也序列化為XML檔案(使用XStream)
用於序列化的實體類Person.java 程式碼如下(記得需要實現Serializable介面):
序列化、反序列化為一般的檔案,SerializeToFlatFile.java類的程式碼如下:import java.io.Serializable; @SuppressWarnings("serial") public class Person implements Serializable{ private String name; private int age; public Person(){ } public Person(String str, int n){ System.out.println("Inside Person's Constructor"); name = str; age = n; } String getName(){ return name; } int getAge(){ return age; } }
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializeToFlatFile { public static void main(String[] args) { SerializeToFlatFile ser = new SerializeToFlatFile(); ser.savePerson(); ser.restorePerson(); } public void savePerson(){ Person myPerson = new Person("Jay",24); try { FileOutputStream fos = new FileOutputStream("E:\\workspace\\2010_03\\src\\myPerson.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); System.out.println("Person--Jay,24---Written"); System.out.println("Name is: "+myPerson.getName()); System.out.println("Age is: "+myPerson.getAge()); oos.writeObject(myPerson); oos.flush(); oos.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public void restorePerson() { try { FileInputStream fis = new FileInputStream("E:\\workspace\\2010_03\\src\\myPerson.txt"); ObjectInputStream ois = new ObjectInputStream(fis); Person myPerson = (Person)ois.readObject(); System.out.println("\n--------------------\n"); System.out.println("Person--Jay,24---Restored"); System.out.println("Name is: "+myPerson.getName()); System.out.println("Age is: "+myPerson.getAge()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
執行結果為(console輸出),當然可以檢視到myPerson.txt檔案已經生成:
Inside Person's Constructor
Person--Jay,24---Written
Name is: Jay
Age is: 24
--------------------
Person--Jay,24---Restored
Name is: Jay
Age is: 24
控制物件的序列化和反序列化
介面 java.io.Externalizable 。當物件實現了這個介面時,就可以靈活的控制它的序列化和反序列過程,這個介面繼承了java.io.Serializable
Externalizable 介面定義了兩個方法,writerExternal方法在序列化時被呼叫,可以再該方法中控制序列化內容,readExternal方法在反序列時被呼叫,可以在該方法中控制反序列的內容
例項:UserInfo
import java.io.*;
import java.util.*;
//本程式通過實現Externalizable介面控制物件序列化和反序列
public class UserInfo implements Externalizable {
public String userName;
public String userPass;
public int userAge;
public UserInfo(){
}
public UserInfo(String username,String userpass,int userage){
this.userName=username;
this.userPass=userpass;
this.userAge=userage;
}
//當序列化物件時,該方法自動呼叫
public void writeExternal(ObjectOutput out) throws IOException{
System.out.println("現在執行序列化方法");
//可以在序列化時寫非自身的變數
Date d=new Date();
out.writeObject(d);
//只序列化userName,userPass變數
out.writeObject(userName);
out.writeObject(userPass);
}
//當反序列化物件時,該方法自動呼叫
public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException{
System.out.println("現在執行反序列化方法");
Date d=(Date)in.readObject();
System.out.println(d);
this.userName=(String)in.readObject();
this.userPass=(String)in.readObject();
}
public String toString(){
return "使用者名稱: "+this.userName+";密碼:"+this.userPass+
";年齡:"+this.userAge;
}
}
改寫測試類
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.lang.management.*;
public class Test {
//序列化物件到檔案
public static void serialize(String fileName){
try
{
//建立一個物件輸出流,講物件輸出到檔案
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(fileName));
UserInfo user=new UserInfo("renyanwei","888888",20);
out.writeObject(user); //序列化一個會員物件
out.close();
}
catch (Exception x)
{
System.out.println(x.toString());
}
}
//從檔案反序列化到物件
public static void deserialize(String fileName){
try
{
//建立一個物件輸入流,從檔案讀取物件
ObjectInputStream in=new ObjectInputStream(new FileInputStream(fileName));
//讀取UserInfo物件並呼叫它的toString()方法
UserInfo user=(UserInfo)(in.readObject());
System.out.println(user.toString());
in.close();
}
catch (Exception x)
{
System.out.println(x.toString());
}
}
public static void main(String[] args) {
serialize("D:\\test.txt");
System.out.println("序列化完畢");
deserialize("D:\\test.txt");
System.out.println("反序列化完畢");
}
}
執行結果
現在執行序列化方法
序列化完畢
現在執行反序列化方法
Thu Oct 23 22:18:12 CST 2008
使用者名稱: renyanwei;密碼:888888;年齡:0
反序列化完畢