Java serialization and deserialization

Source: Internet
Author: User
Objectoutputstream OOS = NULL; try {// determine whether the file exists. If the file exists, first delete the file filestorage = new file (filepath + filename); If (filestorage. exists () {filestorage. delete () ;}// check whether the file path exists. If not, create the folder path if (! New file (filepath ). exists () {New file (filepath ). mkdirs ();} filestorage. createnewfile (); // output the object to the file fileoutputstream Fos = new fileoutputstream (filestorage); OOS = new objectoutputstream (FOS); OOS. writeobject (sessioncontext);} catch (filenotfoundexception e) {Throw (New recoverableexception ("storage file not found", E);} catch (ioexception E) {Throw (New recoverableexception ("file storage error", E);} finally {If ( Oos! = NULL) {try {OOS. Close ();} catch (ioexception e) {Throw (New recoverableexception ("error occurred when closing the storage file", E ));}}}

Objectoutputstream writes the basic data types and graphics of Java objects to outputstream. You can use objectinputstream to read (refactor) objects. Objects can be stored permanently by using files in the stream. If the stream is a network socket stream, you can reconstruct the object on another host or in another process.

Only objects that support the java. Io. serializable interface can be written to the stream. Classes of each serializable object are encoded, including class names and class signatures, object Field Values and array values, and closures of all other objects referenced from the initial object.

The writeobject method is used to write an object into a stream. All objects (including string and array) can be written through writeobject. Multiple objects or elements can be written to the stream. You must use the same type and sequence as when writing objects to read back objects from the corresponding objectinputstream.

You can also use the appropriate method in dataoutput to write basic data types to the stream. You can also use the writeutf method to write strings.

The default serialization mechanism of an object writes the following content: the Object Class, Class signature, and values of non-transient and non-static fields. References to other objects (except transient and static fields) will also cause those objects to be written. You can use the reference sharing mechanism to encode multiple references of a single object, so that the image of the object can be restored to the shape when they were originally written.

For example, to write an object that can be read through the example in objectinputstream, perform the following operations:

        FileOutputStream fos = new FileOutputStream("t.tmp");        ObjectOutputStream oos = new ObjectOutputStream(fos);        oos.writeInt(12345);        oos.writeObject("Today");        oos.writeObject(new Date());        oos.close(); 

Classes that require special processing during serialization and deserialization must implement the following special methods with accurate signatures:

 private void readObject(java.io.ObjectInputStream stream)     throws IOException, ClassNotFoundException; private void writeObject(java.io.ObjectOutputStream stream)     throws IOException 

The writeobject method writes the object state of a specific class so that the corresponding readobject method can restore it. The method itself does not have to be related to the status of the superclass or subclass of the object. The status is saved by writing fields into objectoutputstream using the writeobject method or the method supported by dataoutput for basic data types.

The serialization operation does not write out any object fields that do not implement the java. Io. serializable interface. The subclass of an object that cannot be serialized can be serialized. In this case, a non-serializable class must have a non-parameter constructor to allow initialization of its fields. In this case, the subclass stores and restores the status of non-serializable classes. This type of field is accessible (public, package, or protected), or there are get and set methods that can be used to restore the state.

The writeobject and readobject methods can block Object serialization. At this time, notserializableexception is thrown. Objectoutputstream causes an exception and suspends the serialization process.

The externalizable interface allows the object to assume that the content and format in the serialized form of the object can be fully controlled. Call the externalizable interface (writeexternal and readexternal) to save and restore the object state. During class implementation, they can use all objectoutput and objectinput methods to read and write their own States. The object is responsible for handling any version control.

The serialization of Enum constants is different from that of normal serializable or externalizable objects. The serialization form of an Enum constant only contains its name. The field value of a constant is not transmitted. To serialize an Enum constant, objectoutputstream needs to write a string returned by the constant name method. Like other serializable or externalizable objects, Enum constants can be used as the reference targets for back in serialized streams. The process used to serialize Enum constants cannot be customized; During serialization, all the class-specific writeobjects defined by the enum type
And writereplace methods will be ignored. Similarly, any declaration of the serialpersistentfields or serialversionuid field will also be ignored. All Enum types have a fixed serialversionuid of 0l.

Basic data (excluding the serializable field and externalizable data) is written into objectoutputstream as a block data record. A block data record consists of a header and data. The block data part includes the mark and the number of bytes following the part. Continuous basic write data is merged into a block data record. The partition factor of block data records is 1024 bytes. Each block data record will be filled with 1024 bytes or written when block data mode is terminated. Call the objectoutputstream method writeobject, defaultwriteobject, and writefields.
Initially, only all existing block data records are terminated.

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.