Serializing the deserialization API (entry level)

Source: Internet
Author: User

Defined:

Java Serialization refers to the process of converting a Java object to a sequence of bytes, while Java deserialization refers to the process of reverting a sequence of bytes to a Java object.

Why are strings usually also serialized?

The reason that the object needs to be serialized is to ensure that the state of the object is not changed (for example, a studunet);

Strings are also often serialized because there is no reason to parse them (for example, the encoding may not be inconsistent) (although the string is not serialized normally).

At the same time, the following reasons are also a very important factor:

objects, files, data, there are many different formats, it is difficult to transfer and save uniformly,

After serialization is a byte stream, no matter what the original thing, can become the same thing, you can carry out a common format to transfer or save, transfer

After the loss, to re-use, the deserialization of the restore, so that the object is an object, file or file.

API provided by JDK:

Java.io.ObjectOutputStream: Represents an object output stream

Its writeobject (Object obj) method serializes the Obj object specified by the parameter and writes the resulting sequence of bytes to a target output stream.

Java.io.ObjectInputStream: Represents an object input stream

Its readobject () method reads the sequence of bytes from the source input stream, deserializes them into an object, and returns them.

Requirements to implement serialization

Only an object of a class that implements the serializable or Externalizable interface can be serialized, otherwise an exception is thrown.

Methods for implementing the serialization and deserialization of Java objects

Assuming a student class, its objects need to be serialized, there are three ways to do it:

Method One: If the student class implements only the serializable interface , it can be serialized and deserialized in the following way

ObjectOutputStream uses the default serialization method to serialize non-transient instance variables of the student object.

Objcetinputstream uses the default deserialization method to deserialize non-transient instance variables of the student object.

Method Two: If the student class not only implements the serializable interface, but also defines ReadObject (ObjectInputStream in) and WriteObject (Objectoutputsteam out) , serialization and deserialization are performed in the following manner.

ObjectOutputStream calls the Student object's WriteObject (ObjectOutputStream out) method to serialize.

ObjectInputStream invokes the Student object's ReadObject (ObjectInputStream in) method for deserialization.

Method Three: If the student class implements the externalnalizable interface, and the student class must implement Readexternal (ObjectInput in) and Writeexternal (ObjectOutput out ) method, the serialization and deserialization are performed in the following manner.

ObjectOutputStream invokes the Student object's writeexternal (ObjectOutput Out) method for serialization.

ObjectInputStream invokes the Student object's readexternal (ObjectInput in) method for deserialization.

Steps to serialize:

Step One: Create an object output stream that can wrap a different type of target output stream, such as a file output stream:

ObjectOutputStream out = new ObjectOutputStream (New FileOutputStream ("D:\\objectfile.obj"));

Step two: Write the object through the WriteObject () method of the object output stream:

Out.writeobject ("Hello");

Out.writeobject (New Date ());

Steps to Deserialize:

Step One: Create an object input stream that can wrap a different type of input stream, such as a file input stream:

ObjectInputStream in = new ObjectInputStream (New FileInputStream ("D:\\objectfile.obj"));

Step Two: Read the object through the ReadObject () method of the object output stream:

String obj1 = (string) in.readobject ();

Date Obj2 = (date) in.readobject ();

Serialize deserialization of String data demo:

public class Serializeanddeserialize {

Serialization of
public static byte[] Serialize (Object o) {
ObjectOutputStream oos = null;
Bytearrayoutputstream BAOs = null;
try{
baos= new Bytearrayoutputstream ();
Oos=new ObjectOutputStream (BAOs);
Oos.writeobject (o);
Byte[] Bytes=baos.tobytearray ();
return bytes;
}catch (Exception e) {
E.printstacktrace ();
}
return null;
}

Deserialization
public static Object deserialize (Byte [] bytes) {
Bytearrayinputstream Bai=null;
ObjectInputStream Ois=null;
try {
Bai=new bytearrayinputstream (bytes);
Ois=new ObjectInputStream (BAI);
return Ois.readobject ();
}catch (Exception e) {
E.printstacktrace ();
}
return null;
}

public static void Main (String []args) {
System.out.println (Serialize ("Asdasdasdad"));
SYSTEM.OUT.PRINTLN (Deserialize (Serialize ("Asdasdasdad"));
}
}

To instantiate an entity class:

Entity class:

public class Student implements Serializable

{

private String name;

Public Student ()

{}

Public Student (String name)

{

THIS.name = name;

}

public void SetName (String name)

{

THIS.name = name;

}

Public String GetName ()

{

return this.name;

}

}

Serialization deserialization:

public class Usestudent

{

public static void Main (string[] args)

{

Student st = new Student ("Tom");

File File = new file ("E:\\student.txt");

Try

{

File.createnewfile ();

}

catch (IOException E)

{

E.printstacktrace ();

}

Try

{

Student Object Serialization Process

FileOutputStream fos = new FileOutputStream (file);

ObjectOutputStream oos = new ObjectOutputStream (FOS);

Oos.writeobject (ST);

Oos.flush ();

Oos.close ();

Fos.close ();

Student Object Deserialization Process

FileInputStream fis = new FileInputStream (file);

ObjectInputStream ois = new ObjectInputStream (FIS);

Student st1 = (Student) ois.readobject ();

System.out.println ("name =" + St1.getname ());

Ois.close ();

Fis.close ();

}

catch (ClassNotFoundException e)

{

E.printstacktrace ();

}

catch (IOException E)

{

E.printstacktrace ();

}

}

}

Above.

To be a teacher, to share above

Reference Blog: http://blog.csdn.net/wangloveall/article/details/7992448/

Serializing the deserialization API (entry level)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.