2011年5月24日 星期二

心得 Object Serialization Java

Serialization 簡單的說就是可以將java 物件(object) 儲存成一個位元組起來,下次在讀取的時候在將位元組轉成物件使用

若要 Serialization 在物件必須 implements Serializable 這個 Interface


如以下的 code

import java.io.Serializable;

class MyClass implements Serializable {
String str;
double[] vals;
File fn;

public MyClass(String s, double[] nums, String fname) {
str = s;
vals = nums;
fn = new File(fname);
}

public String toString() {
String data = " str: " + str + "\n vals: ";

for (double d : vals)
data += d + " ";
data += "\n fn: " + fn.getName();

return data;
}
}



呼叫的範例可以參考, 範例簡單的說是將 這個物件存到 obj.dat 的檔案 ,之後再取出來( obj.dat 也可以換成指定的路徑 如 c:/obj.dat )


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {
public static void main(String[] argv) throws Exception {
double v[] = { 1.1, 2.2, 3.3 };
double v2[] = { 9.0, 8.0, 7.7 };

MyClass obj1 = new MyClass("This is a test", v, "Test.txt");
MyClass obj2 = new MyClass("Alpha Beta Gamma", v2, "Sample.dat");

ObjectOutputStream fout = new ObjectOutputStream(new FileOutputStream("obj.dat"));
System.out.println("obj1:\n" + obj1);
fout.writeObject(obj1);
System.out.println("obj2:\n" + obj2);
fout.writeObject(obj2);
fout.close();

ObjectInputStream fin = new ObjectInputStream(new FileInputStream("obj.dat"));
MyClass inputObj;

inputObj = (MyClass) fin.readObject();
System.out.println("First object:\n" + inputObj);

inputObj = (MyClass) fin.readObject();
System.out.println("Second object:\n" + inputObj);
fin.close();
}
}











參考:
[1]:Object serialization with Serializable interface, ObjectOutputStream and ObjectInputStream.
[2]:http://home.so-net.net.tw/idealist/Java/IO.html






沒有留言: