To enable an object to support serialization, you must make its class serializable. That is, this class must implement one of two interfaces: serializable and externalizable.
Serializable is a flag interface that does not need to implement any methods. It only indicates that the instance of this class is serializable.
Class to implement the serializable interface, you can serialize the object of this class.
Procedure:
1. Create an objectoutputstream. The output stream is a processing stream, so it must be built on the basis of other node streams.
Objectoutputstream OOS = new objectoutputstream (New fileoutputstream ("object.txt "));
2. Call the writeobject method of the objectoutstream object to output the serializable object.
Person = new person (11, "AAA", 22 );
Oos. Write (person );
Restore Java objects from binary streams through deserialization
Procedure:
1. Create an objectinputstream. The input stream is a processing stream, which must be based on the stream of other nodes.
Objectinputstream OIS = new objectinputstream (New fileinputstream ("object.txt "));
2. Call the readobfect method of the objectinputstream object to read objects in the stream.
Person P = (person) Ois. readobject ();
Note: deserialization only reads the data of Java objects, rather than Java classes. When deserialization is used to restore a Java object, class files of the classes to which the Java object belongs must be provided, otherwise, a classnotfoundexception exception is thrown.
If multiple Java objects are written to a file using a serialized part, the object must be read in the actual write order when the deserialization mechanism is used to restore the object.
----------------- Excerpt from crazy Java handout