FileDocCategorySizeDatePackage
TestSerializable.javaAPI DocExample1920Sun Feb 24 19:28:24 GMT 2002None

TestSerializable.java

/*
 * TestSerializable.java
 *
 * Created on 24 February 2002, 12:15
 */


/**
 *
 * @author  Administrator
 * @version 
 */
import java.io.*;

public class TestSerializable {
    private PersonSerializable p1 = new PersonSerializable();
    private PersonSerializable p2 = new PersonSerializable();    
    /** Creates new TestSerializable */
    public TestSerializable() {
        p1.setDetails("Fred Bloggs",22,'m',"\u6B22\u8FCE\u4F7F\u7528\u0020");
        p2.setDetails("Amy Hussain",25,'f',"Nuclear Physicist");
    }
    

    public static void main(String[] args) throws IOException{
        
        TestSerializable test = new TestSerializable();
        // Create an binary output stream "test.dat"
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
                               new File("c:\\test.dat")));
        // Save the two person objects
        test.saveAllData(oos);
        // Close the file
        oos.close();
        // Open a binary intput stream "test.dat"
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
                                new File("c:\\test.dat")));
        // Retrieve the two person objects
        test.loadAllData(ois);
        // Close the input stream
        ois.close();
        // display the two person objects.
        test.displayAllData();
    }
    public void saveAllData(ObjectOutputStream oos) throws IOException{
        
        oos.writeObject(p1);
        oos.writeObject(p2);
    }
    public void loadAllData(ObjectInputStream ois) throws IOException {
        try {
        p1 = (PersonSerializable) ois.readObject();
        p2 = (PersonSerializable) ois.readObject();
        }
        catch(ClassNotFoundException c) {
            System.out.println("Cannot find class "+c);
        }
    }
    public void displayAllData() {
        p1.displayDetails();
        p2.displayDetails();
    }
}