Java embodies a simple programming style everywhere. serialization is one of the most commonly used functions. The design in Java is particularly "simple ". With the help of objectinputstream and objectoutputstream, we can easily implement serialization.
As long as our class implements Java. io. the serializable interface can be used to serialize an object using the writeobject () method of objectoutputstream. The read object can be returned using the readobject () method of objectinputstream. The serializable interface does not require any method.
The following is an example, which can give us a perceptual knowledge:
Serial implements the java. Io. serializable interface, which is the class to be serialized. We first construct a serial object serial1 and save (serialize) it in a file, then read (deserialize) it and print its content.
Package stream; /** * @ Author favo Yang */ Import java. Io .*; Public class serial implements serializable { Int company_id; String company_addr; Boolean company_flag; Public serial () {}// different from C ++, no Public serial (INT company_id, string company_addr, Boolean company_flag ){ This. company_id = company_id; This. company_addr = company_addr; This. company_flag = company_flag; } Public static void main (string [] ARGs ){ Serial serial1 = new serial (752, "Dayer Street #5 Building 02-287", false); // construct a new object Fileinputstream in = NULL; Fileoutputstream out = NULL; Objectinputstream oin = NULL; Objectoutputstream oout = NULL; Try { Out = new fileoutputstream ("5.txt "); OOut = new objectoutputstream (out ); Serial1.serialize (oout); // serialization OOut. Close (); OOut = NULL; In = new fileinputstream ("5.txt "); Oin = new objectinputstream (in ); Serial serial = serial. deserialize (Oin); // deserialization System. Out. println (Serial); // print the result } Catch (exception ex ){ Ex. printstacktrace (); } Finally { Try { If (in! = NULL ){ In. Close (); } If (Oin! = NULL ){ Oin. Close (); } If (OUT! = NULL ){ Out. Close (); } If (oout! = NULL ){ OOut. Close (); } } Catch (ioexception ex1 ){ Ex1.printstacktrace (); } } } /** * Deserialize */ Public static serial deserialize (objectinputstream Oin) throws exception { Serial S = (Serial) oin. readobject (); Return S; } Public String tostring (){ Return "data:" + company_id + "" + company_addr + "" + company_flag; } /** * Serialize */ Public void serialize (objectoutputstream oout) throws exception { OOut. writeobject (this ); } } |
Running result:
Data: 752 Dayer Street #5 Building 02-287 false
The result is printed correctly.