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. 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 falseThe result is printed correctly.Currently, the serialization function is not supported by j2s. Therefore, we use DataInputStream and DataoutputStream in combination with rms or network to implement serialization.