Serialization and deserialization of Java

Source: Internet
Author: User
Tags object serialization

What is the serialization and deserialization of Java? Why do I need serialization and deserialization? How do I implement the serialization and deserialization of Java? This paper focuses on these problems.

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.

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. How to implement the serialization and deserialization of Java

1) Serialization API in JDK class library

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.

2) Requirements for serialization

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

3) Methods of 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 only implements the Serializable interface, and 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.

4) steps to serialize in the JDK class library

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 ());

5) steps to deserialize in the JDK class library

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 ();

Note: In order to correctly read the data and complete the deserialization, it is necessary to ensure that the output stream writes objects to the object in the same order as the objects are read from the object input stream.

In order to better understand the Java serialization and deserialization, select the method one encoding implementation.

The student class is defined as follows:

[Java]View Plaincopy
  1. Package Com.jieke.io;
  2. Import java.io.Serializable;
  3. /**
  4. *title: Student Class
  5. *description: Student class that implements the serialization interface
  6. *copyright:copyright (c) 2012
  7. *filename:student.java
  8. * @author Wang luqing
  9. * @version 1.0
  10. */
  11. Public class Student implements Serializable
  12. {
  13. private String name;
  14. private char sex;
  15. private int year;
  16. private double GPA;
  17. Public Student ()
  18. {
  19. }
  20. Public Student (String name,char-sex,int year,double GPA)
  21. {
  22. this.name = name;
  23. this.sex = sex;
  24. this.year = year;
  25. This.gpa = GPA;
  26. }
  27. public void SetName (String name)
  28. {
  29. this.name = name;
  30. }
  31. public void Setsex (char sex)
  32. {
  33. this.sex = sex;
  34. }
  35. public void setyear (int year)
  36. {
  37. this.year = year;
  38. }
  39. public void Setgpa (double gpa)
  40. {
  41. This.gpa = GPA;
  42. }
  43. Public String getName ()
  44. {
  45. return this.name;
  46. }
  47. public Char getsex ()
  48. {
  49. return This.sex;
  50. }
  51. public int getYear ()
  52. {
  53. return this.year;
  54. }
  55. public Double Getgpa ()
  56. {
  57. return This.gpa;
  58. }
  59. }

Serializes the object of the student class to the file O:\\java\\com\\jieke\\io\\student.txt and deserializes it from the file, displaying the result to the console. The code is as follows:

[Java]View Plaincopy
  1. Import java.io.*;
  2. /**
  3. *title: Apply Student class
  4. *description: Realizing the serialization and deserialization of student class instances
  5. *copyright:copyright (c) 2012
  6. *filename:usestudent.java
  7. * @author Wang luqing
  8. * @version 1.0
  9. */
  10. Public class Usestudent
  11. {
  12. public static void Main (string[] args)
  13. {
  14. Student st = New Student ("Tom",' M ',3.6);
  15. File File = new file ("O:\\java\\com\\jieke\\io\\student.txt");
  16. Try
  17. {
  18. File.createnewfile ();
  19. }
  20. catch (IOException e)
  21. {
  22. E.printstacktrace ();
  23. }
  24. Try
  25. {
  26. //student Object Serialization Process
  27. FileOutputStream fos = new FileOutputStream (file);
  28. ObjectOutputStream Oos = new ObjectOutputStream (FOS);
  29. Oos.writeobject (ST);
  30. Oos.flush ();
  31. Oos.close ();
  32. Fos.close ();
  33. //student Object Deserialization process
  34. FileInputStream FIS = new FileInputStream (file);
  35. ObjectInputStream ois = new ObjectInputStream (FIS);
  36. Student st1 = (Student) ois.readobject ();
  37. System.out.println ("name =" + St1.getname ());
  38. System.out.println ("sex =" + st1.getsex ());
  39. SYSTEM.OUT.PRINTLN ("year =" + St1.getyear ());
  40. SYSTEM.OUT.PRINTLN ("GPA =" + St1.getgpa ());
  41. Ois.close ();
  42. Fis.close ();
  43. }
  44. catch (classnotfoundexception e)
  45. {
  46. E.printstacktrace ();
  47. }
  48. catch (IOException e)
  49. {
  50. E.printstacktrace ();
  51. }
  52. }
  53. }

The results are as follows:

Name = Tom

Sex = M

Year = 20

GPA = 3.6

Summarize:

1) Java serialization is the conversion of an object into a sequence of bytes, while the Java deserialization is the restoration of a sequence of bytes to a Java object.

2) The use of Java serialization and deserialization technology, one can achieve the persistence of data, in the MVC pattern is very useful, and the other is the object data can be remote communication.

Reprint Source: http://blog.csdn.net/wangloveall/article/details/7992448

Serialization and deserialization of Java

Related Article

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.