用序列化(Serializable)保存、讀取對象

   實現Serializable藉口的對象可以被轉換成一系列字節,並可以在以後使用時完全恢復原來的樣子。這一過程也可以在網絡中進行,這樣就可以先在windows機器上創建一個對象,對其序列化,然後通過網絡發送給Linux機器,就可以在Linux機器上準確無誤地恢復成原來的樣子。整個過程不必關心數據在不同機器上如何表示,也不必關心字節的順序或其他細節。

      序列化的思想就是“凍結”對象,操作對象(寫到磁盤,通過網絡傳輸等),然後“解凍”對象,重新獲得可用的Java對象。功能的實現要靠ObjectInputStream/ObjectOutputStream類,完全保真原數據,並且開發願意用Serializable。

     實現了Serializable接口的類爲保證serialVersionUID 值跨不同 java 編譯器實現的一致性,序列化類必須聲明一個明確的 serialVersionUID 值。

     ClassA.java

public class ClassA implements Serializable {

	private static final long serialVersionUID = 6013572251564847381L;
	private String name = "My name is a";
	private ClassB b = null;

	ClassA() {
		b = new ClassB();
	}

	public String show() {

		System.out.println("a.toString <a.name=\"" + this.name
				+ "\" a.b.name=\"" + this.b.getName() + "\">");

		return "a.toString <a.name=" + this.name + " a.b.name="
				+ this.b.getName() + ">";
		// \" 雙引號
		// \' 單引號
		// \\ 反斜線
	}

                 .......................
}

    ClassB.java

public class ClassB implements Serializable{

	private static final long serialVersionUID = -4324044767844361076L;

	private String name="My name is b";
	
	ClassB(){}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	
}

將對象內容保存到文本中

WriteSeri.java

public class WriteSeri {

	public static void main(String args[]){
		ObjectOutputStream outObj=null;
		try {
			//將對象內容寫入到文本中
			FileOutputStream  outStr=new FileOutputStream("obj.txt");
			outObj=new ObjectOutputStream(outStr);
			ClassA a=new ClassA();
			outObj.writeObject(a);
			System.out.println("write obj:"+a.show());
			outObj.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
				try {
				if (outObj != null) {
					outObj.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

輸出結果:

a.toString <a.name="My name is a" a.b.name="My name is b">
write obj:a.toString <a.name=My name is a a.b.name=My name is b>

將文本內容還原給對象

ReadSeri.java

public class ReadSeri {

	public static void main(String args[]) {
		ObjectInputStream inObj = null;
		try {
			FileInputStream inStr = new FileInputStream("obj.txt");
			inObj = new ObjectInputStream(inStr);
			ClassA a = (ClassA) inObj.readObject();
			System.out.println("read object:" + a.show());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (inObj != null) {
				try {
					inObj.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

輸出結果:

a.toString <a.name="My name is a" a.b.name="My name is b">
read object:a.toString <a.name=My name is a a.b.name=My name is b>

 

 

 

 

發佈了54 篇原創文章 · 獲贊 0 · 訪問量 3230
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章