Java is the embodiment of a simple programming style, serialization as one of the most common functions, in Java design is particularly "simple." With the help of ObjectInputStream and ObjectOutputStream, we can achieve serialization easily.
As long as our class By implementing the Java.io.Serializable interface, we can serialize an object by using the ObjectOutputStream writeobject () method, and using the ObjectInputStream ReadObject () method, You can return an object that is read out. The serializable interface does not require us to implement any methods.
Here is an example that gives us a sense of sensibility:
Serial implements the Java.io.Serializable interface, which is a class that needs to be serialized. We first construct a serial object Serial1 then save (serialize) it in a file, read it out (deserialize), and print its contents.
package Stream;
/**
* @author favo Yang
*/
Import java.io.*;
public class serial implements S erializable {
int company_id;
String company_addr;
Boolean Company_flag;
Public serial () {}//is different from C + +, no or can
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-2 ", 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 serial2 = serial.Deserialize (oin)//deserialization
System.out.println (SERIAL2);//Print Results
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 E xception{
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.write Object (this);
}
}
Run Result:
data:752 Dayer Street #5 building 02-287 False
The results are printed correctly.