2015-03-04

[Java] Object Serializable 筆記

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

class Address implements Serializable {

    private static final long serialVersionUID = 1L;

    String street;
    String country;

    public Address() {}

    public Address(String s, String c) {
        street = s; country = c;
    }

    public void setStreet(String street){ this.street = street; }
    public String getStreet(){ return this.street; }

    public void setCountry(String country){ this.country = country; }
    public String getCountry(){ return this.country; }

    @Override
    public String toString() {
        return String.format("Street : %s Country : %s", street, country);
    }
}


public class TestSerializable {

    public static void main(String[] args) throws Exception {
        Address addr = new Address("wall street", "united state");

        FileOutputStream fout = new FileOutputStream("address.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(addr);
        oos.close();

        FileInputStream fin = new FileInputStream("address.ser");
        ObjectInputStream ois = new ObjectInputStream(fin);
        Address addr2 = (Address) ois.readObject();
        ois.close();

        System.out.println(addr2);
        // Street : wall street Country : united state
    }
}

參考自:
How to read an Object from file in Java : Mkyong
How to write an Object to file in Java : Mkyong
Understand the serialVersionUID : Mkyong

0 回應: