Java serialization and deserialization

Source: Internet
Author: User
Tags object serialization serialization

I. The concept of serialization and deserialization

  The process of converting an object to a sequence of bytes is called serialization of an object .
  The process of reverting a sequence of bytes to an object is called deserialization of the object .
There are two main uses for serialization of objects:
1) The object's byte sequence is permanently saved to the hard disk, usually stored in a file;
2) A sequence of bytes that transmits an object over the network.

In many applications, some objects need to be serialized to leave the memory space and stay on the physical hard disk for long-term storage. For example, the most common is the Web server session object, when there are 100,000 users concurrent access, there may be 100,000 session objects, memory may be unbearable, so the Web container will be some seesion first serialized to the hard disk, and so on, Restore the objects that were saved to the hard disk in memory.

When two processes are communicating remotely, each other can send various types of data. Regardless of the type of data, it is transmitted over the network in the form of a binary sequence. The sender needs to convert the Java object to a sequence of bytes to be transmitted over the network, and the receiver needs to revert the byte sequence back to the Java object.

Second, the serialization API in the JDK class library

Java.io.ObjectOutputStream represents an object output stream, and 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, and its readobject () method reads a sequence of bytes from a source input stream, deserializes them into an object, and returns them.
only objects of classes that implement the serializable and Externalizable interfaces can be serialized. The Externalizable interface inherits from the serializable interface, and the class that implements the Externalizable interface controls the serialization behavior entirely by itself, whereas classes that implement the serializable interface can take the default serialization method.
object serialization consists of the following steps:
1) Create an object output stream, which can wrap a different type of target output stream, such as a file output stream;
2) writes an object through the WriteObject () method of the object output stream.

the steps for deserializing an object are as follows:
1) Create an object input stream, which can wrap a different type of source input stream, such as a file input stream;
2) The object is read through the ReadObject () method of the object input stream.

 Public classPersonImplementsSerializable {/*** Serialization ID*/    Private Static Final LongSerialversionuid = -5809782578272943999l; Private intAge ; PrivateString name; PrivateString sex;  Public intGetage () {returnAge ; }     PublicString GetName () {returnname; }     PublicString Getsex () {returnsex; }     Public voidSetage (intAge ) {         This. Age =Age ; }     Public voidsetName (String name) { This. Name =name; }     Public voidsetsex (String sex) { This. Sex =sex; }}
 Public classTestobjserializeanddeserialize { Public Static voidMain (string[] args)throwsException {Serializeperson ();//serializing A Person objectPerson P = Deserializeperson ();//anti-sequence Perons objectSystem.out.println (Messageformat.format ("Name={0},age={1},sex={2}", p. getName (), P.getage (), P.getsex ()); }    /*** Methodname:serializeperson Description: Serialize Person Object * *@authorXUDP *@throwsFileNotFoundException *@throwsIOException*/    Private Static voidSerializeperson ()throwsFileNotFoundException, IOException { person person=NewPerson (); Person.setname ("GaCl"); Person.setage (25); Person.setsex (Male); //ObjectOutputStream//object output stream, storing the person object in the E-drive's Person.txt file, completing the serialization of the Person objectObjectOutputStream oo =NewObjectOutputStream (NewFileOutputStream (NewFile ("E:/person.txt")));        Oo.writeobject (person); System.out.println ("Person object serialization succeeded!" ");    Oo.close (); }    /*** Methodname:deserializeperson Description: Anti-Sequence Perons object * *@authorXUDP *@return     * @throwsException *@throwsIOException*/    Private StaticPerson Deserializeperson ()throwsException, IOException {objectinputstream ois=NewObjectInputStream (NewFileInputStream (NewFile ("E:/person.txt"))); Person Person=(person) ois.readobject (); System.out.println ("The person object was deserialized successfully!" "); returnPerson ; }}

The serialized person succeeds in generating an Person.txt file on the e-disk, and the deserialization of the person is reading the e-disk Person.txt into a person object

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.