[javaSE] IO流(對象序列化),javase序列化
寫入
擷取ObjectOutputStream對象,new出來,構造參數:FileOutputStream對象目標檔案
調用ObjectOutputStream對象的writeObject()方法,參數:要儲存的對象
調用ObjectOutputStream對象的close()方法,關閉流
此時會報異常,NotSerialzeableException,是因為目標類沒有實現Serializable介面,這個介面沒有方法,稱為標記介面,會在改變類之後,產生新的序號,儲存的檔案讀取時會顯示錯誤資訊InvalidClassException
讀取
擷取ObjectInputStream對象,new出來,構造參數:FileInputStream對象目標檔案
調用ObjectInputStream對象的readObject()方法,得到儲存的資料
import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;public class ObjectStreamDemo { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { writeObj(); readObj(); } /** * 儲存對象 * @throws IOException * @throws FileNotFoundException */ public static void writeObj() throws Exception{ ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("person.object")); oos.writeObject(new Person("taoshihan",100)); } public static void readObj() throws Exception{ ObjectInputStream ois=new ObjectInputStream(new FileInputStream("person.object")); Person person=(Person) ois.readObject(); System.out.println(person);//輸出 taoshihan:100 }}/** * 自訂的類 * @author taoshihan * */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() { // TODO Auto-generated method stub return name+":"+age; }}
PHP版:
<?phpclass Person{ private $name; private $age; public function __construct($name,$age){ $this->name=$name; $this->age=$age; } public function toString(){ return $this->name.":".$this->age; }}$personObj=serialize(new Person("taoshihan",100));echo $personObj;// 輸出 O:6:"Person":2:{s:12:"Personname";s:9:"taoshihan";s:11:"Personage";i:100;}$obj=unserialize($personObj);echo $obj->toString();//輸出 taoshihan:100