【Java學習筆記】對象的流讀寫(序列化)

來源:互聯網
上載者:User

作者:gnuhpc
出處:http://www.cnblogs.com/gnuhpc/

Serializable介面中沒有任何的方法。當一個類聲明要實現Serializable介面時,只是表明該類參加序列化協議,而不需要實現任何特殊的方法。

注意:Thread類不能被並行化

import java.io.Serializable;
public class Goober implements Serializable {
    private int width;
    private String color;
    private transient long work;//若你的類中有不能並行化的或者不想並行化的成員,則使用transient進行忽略
    Goober() {
        width = 99;
        color = "puce";
    }
    void setColor(String setting) {
        color = setting;
    }
    String getColor() {
        return(color);
    }
}

========寫=======

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
public class SerialDemo1 {
    public static void main(String arg[]) {
        Goober goober = new Goober();
        goober.setColor("magenta");
        try {
            FileOutputStream fos = new FileOutputStream("sergoob");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(goober);
            oos.close();
        } catch(IOException e) {
            System.out.println(e);
        }
    }
}

========讀=======

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
public class SerialDemo2 {
    public static void main(String arg[]) {
        Goober goober = null;
        try {
            FileInputStream fis = new FileInputStream("sergoob");
            ObjectInputStream ois = new ObjectInputStream(fis);
            goober = (Goober)ois.readObject();
            ois.close();
        } catch(IOException e) {
            System.out.println(e);
        } catch(ClassNotFoundException e) {
            System.out.println(e);
        }
        String color = goober.getColor();
        System.out.println(color);
    }
}

注意:

1.Demo1和Demo2都要求有Goober這個類,也就是說,實質上,方法本身並沒有因為序列化而儲存在檔案中。

2.真正的對象持久化建議使用關係型資料庫或者XML檔案,通用性較高,而序列化要求雙方都是Java才可以。

 

作者:gnuhpc
出處:http://www.cnblogs.com/gnuhpc/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.