[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; }

    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);

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

        // 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 回應: