Serialization is generally used in the following scenarios:
1. Save the object permanently and save the object to the local file through a serialized byte stream;
2. Transfer objects on the network through serialization
3. Pass objects between processes through serialization
The code copy is as follows:
import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class javaSerializable_fun {
/**
* java.io.Serializable interface, the class can only be serialized if it implements the excuse of Serializable.
* java.io.Externalizable interface, using java serialization and deserialization tools, many tasks of storing and restoring objects can be automatically completed.
* java.io.ObjectOutput interface, serialization is passed out, inherits the DataOutput interface and defines some methods, which supports object serialization;
* Highlights: In this class, the writeObject() method is the most important method, used for object serialization. If the object contains other object references, the writeObject() method serializes these objects;
* java.io.ObjectOutputStream class, responsible for writing objects into the stream, constructing method: ObjectOutputStream(OutputStream out);
* java.io.ObjectInput interface, serialize in. Inherited the DataInput interface and defined some methods, it supports object serialization;
* ObjectInputStream class, responsible for reading objects into the stream, constructing method: ObjectInputStream(InputStream out);
***/
public static void main(String[] args) {
try
{
//Construct FileOutputStream object
FileOutputStream f=new FileOutputStream("C:a.txt");
//Construct the ObjectOutputStream object
ObjectOutputStream out=new ObjectOutputStream(f);
Customer customer=new Customer("bj",50);
//Serialize using the writeObject() method of the ObjectOutputStream object
out.writeObject(customer);
//Close the ObjectOutputStream object
out.close();
//Close FileOutputStream object
f.close();
System.out.println("Serialization is complete!");
}
catch(IOException e)
{
e.getStackTrace();
}
}
}
class Customer implements Serializable
{
private static final long serialVersionUID =1L;
private String name;
private int age;
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public Customer(String name,int age)
{
this.name=name;
this.age=age;
}
public String toString()
{
return "name="+ name +",age="+age;
}
}