對象的二進制輸入/輸出

package ten;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;



/**
 * @author mz
 * 學習ObjectOutputStream類和ObjectInputStream類
 *
 */

public class ObjectIODemo {
    public static void main(String[] args) {
        try {
            ObjectOutputStream  out = new ObjectOutputStream(new FileOutputStream("luling"));

            //建三個對象
            BeautifulPerson one = new BeautifulPerson("Zhang Jingran", 18);
            BeautifulPerson two = new BeautifulPerson("Zhang Yiran", 17);
            BeautifulPerson three = new BeautifulPerson("Mu Haidong", 27);

            //將三個對象寫入文件
            out.writeObject(one);
            out.writeObject(two);
            out.writeObject(three);
            
            //關(guān)閉流和文件的連接
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        try {
            ObjectInputStream  in = new ObjectInputStream(new FileInputStream("luling"));
            
            BeautifulPerson readOne = (BeautifulPerson) in.readObject();
            BeautifulPerson readTwo = (BeautifulPerson) in.readObject();
            BeautifulPerson readThree = (BeautifulPerson) in.readObject();

            System.out.println(readOne);
            System.out.println(readTwo);
            System.out.println(readThree);
            
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

    }
}

class BeautifulPerson implements Serializable {
    private String name;
    private int age;
    
    public BeautifulPerson() {
        name = null;
        age = 0;
    }
    
    public BeautifulPerson(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    //為了輸出Person類,一定要有一個toString方法。
    public String toString() {
        return "name: " + name + ", " + "age: " + age;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容