[javaSE] IO流(對象序列化),javase序列化

來源:互聯網
上載者:User

[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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.