CIS-123 Home http://www.c-jump.com/bcc/c123c/c123syllabus.htm
Once object is created, data attributes occupy memory that belongs to the object.
Objects are always in some kind of state.
When the application terminates, objects are destroyed and memory is freed.
However, state of each object can be preserved on a permanent media.
Objects that are preserved in this way are called persistent objects.
Serialization is the process of writing the state of an object to a byte stream.
Byte stream is simply a memory buffer provided to us by the system environment.
Byte stream is very easy to store in a file and restore from the file afterwards.
Restoring object state from a byte stream is called deserialization.
Serialization can be complex when an object has references to other objects;
in such case writing and restoring state of all objects needs to be
properly ordered
arranged to restore both the objects and the references to them.
Only object that implements Serializable interface can be saved and restored by the serialization facilities.
Serializable interface defines no operations.
Why? Because the Serializable interface only indicates that a class may be serialized.
import java.util.*; import java.io.*; class Person implements Serializable{ private String name; public Person() { } public Person( String n ){ System.out.println("In Person ctr"); name = n; } String getName() { return name; } }
import java.util.*; import java.io.*; public class SavePerson { public static void main(String args[]){ Person person = new Person( "Jack Jones" ); try { FileOutputStream fos = new FileOutputStream( "Name.txt" ); ObjectOutputStream oos = new ObjectOutputStream( fos ); System.out.print( "Person Name Written: " ); System.out.println( person.getName() ); oos.writeObject( person ); oos.flush(); oos.close(); } catch(Exception e){ e.printStackTrace(); } } }
import java.io.*; import java.util.*; public class RestorePerson{ public static void main( String args[] ) { try{ FileInputStream fis = new FileInputStream( "Name.txt" ); ObjectInputStream ois = new ObjectInputStream( fis ); Person person = ( Person ) ois.readObject(); System.out.print( "Person Name Restored: " ); System.out.println( person.getName() ); ois.close(); } catch ( Exception e ) { e.printStackTrace(); } } }