The serialization and deserialization of Java objects using

Source: Internet
Author: User

1.Java Serialization and deserialization

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.

2. Why serialization and deserialization are required

We know that when two processes communicate remotely, they can send each other various types of data, including text, pictures, audio, video, etc., which are transmitted over the network in the form of a binary sequence. So when two Java processes are communicating, can we implement the inter-process object transfer? The answer is yes. How do we do that? This requires the serialization and deserialization of Java. In other words, on the one hand, the sender needs to convert the Java object to a sequence of bytes and then transfer it over the network, on the other hand, the receiver needs to recover the Java object from the sequence of bytes. The basic principle and the network communication is consistent, through the special encoding way: Writes the object and its internal data encoding, exists in the array or the file inside then sends to the destination, decodes, reads the data. OK here to show that we can use it.

After we have clarified why Java serialization and deserialization are needed, we naturally think of the benefits of Java serialization. The advantage of this is the persistence of data, through serialization can be permanently saved to the hard disk (usually stored in the file), the second, the use of serialization to achieve remote communication, that is, the transmission of the object's byte sequence on the network.

3. Serialization of objects

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. only objects of classes that implement the serializable and Externalizable interfaces can be serialized.

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.

1, serialized stream: The object in the same way as the flow of text or transmission in the network;  Object---> Flow: ObjectOutputStream 2, deserialization stream: Restores the stream object data in the text file or the stream object data in the network to the object.   Stream---> Objects: ObjectInputStream
//------------------------------------
The first code, after assigning a serialized object to a file that corresponds to the write () method, then reads the data in the file and restores the data to the object read () method.
1 ImportJava.io.FileInputStream;2 Importjava.io.FileNotFoundException;3 ImportJava.io.FileOutputStream;4 Importjava.io.IOException;5 ImportJava.io.ObjectInputStream;6 ImportJava.io.ObjectOutputStream;7 8 /*9 * Serialized stream: The object is stored in the same way as the text or transmitted in the network; Object---> Flow: ObjectOutputStreamTen * Deserialization stream: Restores the stream object data in the text file or the stream object data in the network to the object. Stream---> Objects: ObjectInputStream One  */ A  Public classObjectstreamdemo { -      Public Static voidMain (string[] args)throwsIOException { -         //serializing the data is actually writing the object to a text file the         //write (); - read (); -     } -  +     Private Static voidRead ()throwsIOException { -         //creating a deserialization stream object +ObjectInputStream Ois =NewObjectInputStream (NewFileInputStream ( A"A.txt")); at         //read, restore objects -         Try { -Person p =(person) ois.readobject (); - System.out.println (p.tostring ()); -}Catch(ClassNotFoundException e) { -             //TODO auto-generated Catch block in e.printstacktrace (); -         } to          + ois.close (); -     } the  *     Private Static voidWrite ()throwsIOException { $         //creating a serialized stream objectPanax Notoginseng         //Public ObjectOutputStream (OutputStream out) -ObjectOutputStream Oos =NewObjectOutputStream (NewFileOutputStream ( the"A.txt")); +         //Creating Objects APerson p =NewPerson ("Java", 20); the Oos.writeobject (p); +         //Freeing Resources - oos.close (); $     } $}

------------------------------Object Classes

Sometimes when we modify a point of the object's class, the serialized object cannot be read because the system defaults to an ID when the object is serialized, and the ID will change once the class is modified.

cannot be matched when reading, so the compiler prompts us to add an ID through the yellow line, so that the ID of the default defaults can also be generated ID, I generally use generated.

1 Importjava.io.Serializable;2 3 /*4 * Notserializableexception is a serialized exception,5 * This class needs to implement an interface: the serializable serialization interface, which does not have any methods, just as an identity. 6 * An interface similar to this that has no method is the tag interface7  * 8  * !!! Every time you go to modify the class, a new serialized identity value will be generated! , need to re-new, reread, this is the basic method. 9 * Find a way to fix the identity ID of the class, set it artificially. This way, even if you modify the contents of the class again, you can guarantee that the ID is fixed, and that it always matches when it is read. Ten * Add generated serial version ID, click the yellow in the class directly, add a change ID value One  */ A  - /* - * When there are member variables that do not need to be serialized: how to resolve them.  the * method uses the Transient keyword to declare member variables that do not require serialization -  */ -  Public classPersonImplementsserializable{ -  +     /** - * Serialversionuid +      */ A     private static final long serialversionuid = -9164765814868887767l ; at      -     PrivateString name; -     Private transient intAge ; -  -      PublicPerson () { -         Super(); in     } -  to      PublicPerson (String name,intAge ) { +         Super(); -          This. Name =name; the          This. Age =Age ; *     } $ Panax Notoginseng      PublicString GetName () { -         returnname; the     } +  A      Public voidsetName (String name) { the          This. Name =name; +     } -  $      Public intGetage () { $         returnAge ; -     } -  the      Public voidSetage (intAge ) { -          This. Age =Age ;Wuyi     } the  - @Override Wu      PublicString toString () { -         return"Person [name=" + name + ", age=" + Age + "]"; About     } $  -}

The above serialization simply describes the role of serialization, in Android development we can not in order to pass an object to re-add a file inside the apk file to hold the object's data, so in the Android development room

Directly using an array of character sequences to temporarily save the serialized binary values.

Http://www.cnblogs.com/fuck1/p/5459660.html has a detailed method of use in this.

The serialization and deserialization of Java objects using

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.