2015年10月12日 星期一

Serializable 的應用

範例:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

public class Stock implements Serializable{
    private static final long serialVersionUID = 100L;
    private String symbol;
    private int shares;
    private double purchasePrice;
    private transient double currPrice;

    public Stock(String symbol, int shares, double purchasePrice) {
        this.symbol = symbol;
        this.shares = shares;
        this.purchasePrice = purchasePrice;
        setStockPrice();
    }
    
    private void setStockPrice() {
        this.currPrice = this.purchasePrice;
    }
     
    private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException{
        ois.defaultReadObject();
        setStockPrice();
    }
}

import java.io.FileInputStream;
import java.io.Serializable;
import java.util.Set;

public class Portfolio implements Serializable{
    public transient FileInputStream inputFile;
    public static int BASE = 100;
    private transient int totalValue = 10;
    private Set stocks;
 
    Portfolio(Stock s1, Stock s2, Stock s3) {
        this.stocks.add(s1);
        this.stocks.add(s2);
        this.stocks.add(s3);
    }  
}

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

public class Demo {
    public static void main(String[] args){
    
        Stock s1 = new Stock("ORCL",100, 32.5);
        Stock s2 = new Stock("AOOL",100, 245);
        Stock s3 = new Stock("GOGL",100, 54.67);
        
        Portfolio p = new Portfolio(s1,s2,s3);
        
        try(FileOutputStream fos = new FileOutputStream(args[0]);
            ObjectOutputStream out = new ObjectOutputStream(fos)){
            out.writeObject(p);
        } catch (IOException ex) {
           System.out.println("Exception writing out Portfolio :" + ex);
        }
        
        try(FileInputStream fis = new FileInputStream(args[0]);
            ObjectInputStream in = new ObjectInputStream(fis)){
            Portfolio newP = (Portfolio)in.readObject();
        } catch (ClassNotFoundException | IOException ex) {
           System.out.println("Exception reading in Portfolio :" + ex);
        }
    }
}