/*
 * This File is one of the examples from Java Application Development
 * Do not reproduce this code for others or use it in a commercial setting without prior permission from the author.
 */

package serializationExample;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;
import salesApplication.PriceList;

/**
 *
 * @author Matthew Gregory
 * @website www.matthewgregory-author.com.au
 *
 */
public class TestSerialization {
    public static void main(String[] args) {
        //Create an instance of a non serializable object
//        NonSerializableObject myTest = new NonSerializableObject();
        //try to save it
//        write(myTest);
        //Create an instance of a serializable object
        SerializableObject myTest = new SerializableObject();
        //save it
//        write(myTest);
//        System.out.println("Object writen: "+myTest);
        //read it and print it
//        System.out.println("Object read: "+read());  
        //Try to read it into an object of a different class (even with identical structure!
//        SerializableObjectCopy identical = (SerializableObjectCopy) read();
        //Try to read it into an object of an update version of the same class
        //1. update the object 2. comment out the read 3. run the write.
        SerializableObject updated = (SerializableObject) read();
        System.out.println("Object read: "+updated);  
    }
    
    public static void write(Object o){
        try (FileOutputStream fos = new FileOutputStream("myobject");
            ObjectOutputStream out = new ObjectOutputStream(fos);){
            out.writeObject(o);
        } catch (IOException ex) {
            System.out.println(ex);
        }
    }
    
    public static Object read(){
        try (FileInputStream fis = new FileInputStream("myobject")){
            ObjectInputStream in = new ObjectInputStream(fis);
            return in.readObject();
        } catch (ClassNotFoundException | IOException ex) {
            System.out.println(ex);
            return null;
        } 
    }
}