How to serialize an object in Java

Source: Internet
Author: User
Tags serialization

Transferred from: http://blog.csdn.net/chx10051413/article/details/40784667

Http://www.cnblogs.com/baoendemao/p/3804797.html

How to serialize an object in Java

We all know that there is no way to save an object to a text file in Java, but when we have this requirement, we can use the Java Serialization feature to save some of the properties of the current object in binary form to the file. When we need this object, we just need to restore it from the binary to the pre-save object. From here we can be inspired, if you want to send a student object on machine A to machine B, we can serialize the student object into binary, and then send the binary to machine B, machine B can be restored according to the binary data into student object, This implements the function of propagating objects between machines in a disguised manner.

Writes serialized data to a file, primarily two objects, one object is a FileOutputStream object, and the other is a ObjectOutputStream object, ObjectOutputStream is responsible for writing serialized objects to the specified stream. When serializing data is read from a file, it requires two objects, one is FileInputStream, one is a ObjectInputStream object, and ObjectInputStream is responsible for reading the serialized data from the specified stream and reverting it to the object before it is serialized. In addition, the serialized read data and write the same order, for example, we serialize the first write data A, then write B, and finally write C; then we read the data, read the first data is a, read the second data is B, the last read to the data is C, that is: first Write first read the principle.

When serializing an object, this object must implement the Java.io.Serializable interface, which does not contain any methods in the Serializable interface, which can be understood as declaring that the object is a method that can be serialized. When we serialize an object, some properties we don't want to serialize (which can reduce the amount of data), then we can declare that the property is transient (declared with the transient keyword). In addition, static fields are not serialized.

When we serialize an object, if the object does not overwrite the WriteObject or ReadObject method, the system is serialized using the default method, and if there are two methods in the serialized object, the two methods in the object are serialized. As for how to find these two methods, through the code we can trace to whether the object is to overwrite the two methods according to the reflection method. In addition, the two methods in the object are

The flow we're talking about is all about memory, such as why printing to the screen is System.out.println (), while waiting for the user to input from the screen is system.in? Because for memory, the string printed to the screen from memory to the screen of the display, that is, output, and from the screen waiting for user input? is to wait for the keyboard to enter characters into memory.

So, you don't have to memorize, when you encounter Io, think of two things, first, my memory is the center, the second look at the direction of the stream (vector)!

Well, what about writing the file on the hard drive out or in? Do not see "write" File you say in, that is words too literally, you see, write file Flow, is memory----------> hard disk Memory as the center, to the hard disk, OK with out so that is FileOutputStream, bufferedoutputstream and so on
What about reading the papers? Memory <---------------hard drive then in, see the flow of data is ok!

So I go to the Internet and see what the Web is about? Network---------------> Memory is in because we access the page is to crawl the page to get an HTML file, then I would like to enter the network account password login? is not the memory of things to write to the server, so of course is out!

In the same way, socket programming uses more IO, which is explained by server and client respectively.

Server: Encountered a request, network-----> Memory in Server answer, memory-------> network out
----------------------------------------------------------------------------------------------
Client: Request Service, Memory-----> Network out server answer, network-------> Memory in

Got confused? Then you do not think too much, just think that the memory of the data out is out of the peripheral things into memory on the

The Java serialization technique allows you to write the state of an object into a byte stream, and you can read the data in that byte stream from somewhere else and reconstruct the same object. This mechanism allows you to propagate objects through the network, and can persist objects to databases, files and other systems at any time. The serialization mechanism of Java is the technical foundation of RMI, EJB and so on. Purpose: Use the serialization of the object to save the current working state of the application, and will automatically revert to the last state of execution the next time it is started.

Serialization is a mechanism for dealing with the flow of objects, so-called object flow is the flow of the object's contents. It is possible to read and write to a Fluidized object, or to transfer the streamed object between the networks. Serialization is a problem that is raised when reading and writing to an object stream.

Serialization implementation: Implement the Serializable interface for the class that needs to be serialized, and then use an output stream (for example: FileOutputStream) to construct an ObjectOutputStream (object flow) object, and then Using the WriteObject (Object obj) method of the ObjectOutputStream object, you can write out (that is, save its state) the object with the parameter obj, and then use the input stream to recover.

2, the characteristics of serialization:

(1) If a class can be serialized, its subclasses can also be serialized. If the class has a parent class, consider it in two cases if the parent class already implements a serializable interface. The corresponding fields and properties of the parent class are treated the same as the class, and if the parent class of the class does not implement a serializable interface, all field properties of the class's parent class will not be serialized.

(2) member data declared as static and transient types cannot be serialized. Because static represents the state of the class, transient represents the temporary data of the object;

(3) Related classes and interfaces: the classes and interfaces provided in the Java.io package that involve serialization of objects are ObjectOutput interfaces, ObjectOutputStream classes, objectinput interfaces, ObjectInputStream classes.

(1) ObjectOutput interface: It inherits the DataOutput interface and supports serialization of objects, where the WriteObject () method implements the storage of an object. ObjectInput interface: It inherits the Datainput interface and supports serialization of the object, and its ReadObject () method implements reading an object.

(2) ObjectOutputStream class: It inherits the OutputStream class and implements the ObjectOutput interface. This class is used to implement storing objects (calling the WriteObject () method in the ObjectOutput interface). ObjectInputStream class: It inherits the InputStream class and implements the ObjectInput interface. This class is used to implement reading an object (call the ReadObject () method in the ObjectInput interface).

For the processing of the parent class, if the parent class does not implement a serialized interface, it must have a default constructor (that is, a constructor without parameters). Otherwise, you will get an error when compiling. The default constructor is called when the crossdress is being serialized. However, if the parent class is marked as serializable, its default constructor is not called when the crossdress is serialized. What is this for? This is because Java crossdress the serialized object by fetching its object data directly from the stream to produce an object instance, rather than through its constructor.

Import java.io.*;

public class Cat implements Serializable {

private String name;

Public Cat () {

THIS.name = "New Cat";

}

Public String GetName () {

return this.name;

}

public void SetName (String name) {

THIS.name = name;

}

public static void Main (string[] args) {

Cat cat = new Cat ();

try {

FileOutputStream obtains a file stream, ObjectOutputStream the link object and the file stream, writes the object to the hard disk through the WriteObject method, writes from the memory object to the hard disk, therefore is the out stream

FileOutputStream fos = new FileOutputStream ("Catdemo.out");

ObjectOutputStream oos = new ObjectOutputStream (FOS);

System.out.println ("1>" + cat.getname ());

Cat.setname ("My Cat");

Oos.writeobject (CAT);

Oos.close ();

} catch (Exception ex) {ex.printstacktrace (); }

try {

Writes the object in the hard disk file to memory, so it is the in stream

FileInputStream fis = new FileInputStream ("Catdemo.out");

ObjectInputStream ois = new ObjectInputStream (FIS);

Cat = (cat) ois.readobject ();

System.out.println ("2>" + cat.getname ());

Ois.close ();

} catch (Exception ex) {

Ex.printstacktrace ();

}

}

}//writeobject and ReadObject are thread-safe in themselves and are not allowed to be accessed concurrently during transmission. So the object can be passed on one after the other.

How to serialize an object in Java (GO)

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.