寫入
獲取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版:
<?php class 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