Java those little-known serialization (Debug)

Source: Internet
Author: User

One: Cause

Java provides a mechanism called serialization, in fact, the object of the entity class (Bean object) in the form of binary storage and transport (read), there are many objects need to serialize the corresponding class needs to inherit the interface Serializable.

(1) Persist a Java object with an ordered format or sequence of bytes that contains the object's data, the type of the object, and the type of data saved in the object. So, if we have serialized an object, it can be read and deserialized through the object's type and other information, and eventually get the prototype of the object.
(2) ObjectInputStream and ObjectOutputStream objects are high-level stream objects that contain methods for serialization and deserialization. ObjectOutputStream has many methods for serializing objects, most commonly:
(3) Where is serialization required? Serialization is typically used where data is transferred over the network, or when the object is saved to a file. The data that is said here is the object, not the text.
The problem now is that both our network architecture and the hard disk recognize only binary and byte, not Java objects. Serialization is the translation of value/states in Java objects into bytes to be transmitted over the network or saved. In addition, deserialization is done by reading the bytecode and translating it back to the Java object

Two: Example

(1) Employee entity class (Employee.java is a bean that contains the Get Set method)

Import Java.io.serializable;public class Employee implements serializable{     int employeeId;    String EmployeeName;    String Department;         public int Getemployeeid () {        return employeeId;    }    public void Setemployeeid (int employeeId) {        This.employeeid = employeeId;    }    Public String Getemployeename () {        return employeename;    }    public void Setemployeename (String employeename) {        this.employeename = EmployeeName;    }    Public String getdepartment () {        return department;    }    public void Setdepartment (String department) {        this.department = Department;    }}
(2) Here to store in the external file as an example, the external file named Employee.out (file read and write to the Employee class object)

Import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.objectoutputstream;import Java.util.ArrayList; public class Serializemain {/** * @author ZYP */public static void main (string[] args) {Employee emp = new Employe  E ();  Emp.setemployeeid (101);  Emp.setemployeename ("Zyp Zhang Yanpeng");  Emp.setdepartment ("Com.CS");  Employee EMP2 = new Employee ();  Emp2.setemployeeid (102);  Emp2.setemployeename ("Xqz Xu Qin");  Emp2.setdepartment ("Ocean University");  arraylist<employee> emps = new arraylist<employee> ();  Emps.add (EMP);  Emps.add (EMP2);   The above two try {fileoutputstream fileout = new FileOutputStream ("Employee.out", true) for testing; Employee.ser This is the file name, equivalent to the contents of the serialized file name, cannot be viewed with a normal text viewer objectoutputstream OutStream = new ObjectOutputStream (   Fileout);   for (int i=0;i<emps.size (); i++) {Outstream.writeobject (Emps.get (i));   System.out.println (Emps.get (i));   } outstream.writeobject (null);//Very critical Oh, otherwise the error peekbyte wrong, used to read the time of the Empty Outstream.close (); Fileout.close();  }catch (IOException i) {i.printstacktrace (); } }}
(3) Read (2) the stored file

Import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.util.ArrayList; public class Deserializemain {/** * @author ZYP */public static void main (string[] args) {arraylist<employee>   Emps = new arraylist<employee> ();       Employee emp = null;          try {fileinputstream fis =new fileinputstream ("Employee.out"); Employee.ser This is the name of the previously saved file, equivalent to reading the contents of the serialized file name, cannot be viewed with a normal text viewer objectinputstream Ois = new ObjectInputStream (FIS)          ;          EMP = (Employee) ois.readobject ();//while (Emp!=null) {emps.add (EMP);          EMP = (Employee) ois.readobject ();          } ois.close ();       Fis.close ();          }catch (IOException i) {i.printstacktrace ();       Return          }catch (classnotfoundexception c) {System.out.println ("Employee class not Found");          C.printstacktrace ();       Return } for (int i=0;i<emps.size (); i++) {      EMP = Emps.get (i);           System.out.println ("deserialized Employee ...");           SYSTEM.OUT.PRINTLN ("EMP ID:" + emp.getemployeeid ());           System.out.println ("Name:" + emp.getemployeename ());           System.out.println ("Department:" + emp.getdepartment ());       SYSTEM.OUT.PRINTLN (EMP); }        }}
(4) Precautions:

Outstream.writeobject (NULL); (2) In this sentence, very critical, oh, otherwise the error peekbyte wrong, this is used to read the time of the empty, no one to the end of the file EOF is still reading the employee object, is sure to error, errors as follows (if there is no such code)


Error hints


(5) Employee.out file is a 16 binary data storage, the general notepad++ text file cannot open, UE can open the View 16 binary code

(6) Eclipse debugging instructions: First turn on debug mode (view), then set breakpoints (set multiple breakpoints)


Java those little-known serialization (Debug)

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.