Serialization is a mechanism for processing object streams. Object streams are called object streams that stream object content. You can perform read and write operations on Streaming objects, or transfer streaming objects between networks. Serialization aims to solve the problems caused by read/write operations on Object streams. Serialization implementation: implement the Serializable interface for the class to be serialized, and then construct an ObjectOutputStream (Object stream) object using an output stream (for example, FileOutputStream). Then, you can use the writeObject (Object obj) method of the ObjectOutputStream Object to write the Object whose parameter is obj (that is, save its status). To restore the Object, you can use the input stream. Serialization must be used when writing and reading objects:
import java.io.*; class Product implements Serializable { private static final long serialVersionUID = 1L; private float price; private float tax; public Product(float price) { this.price = price; tax = (float)(price*0.20); } public String toString() { return "price:"+price+",tax:"+tax; } } public class CmdDemo { public static void main(String[] str) throws Exception { Product p1 = new Product(100); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("d:\\product.txt")); os.writeObject(p1); os.close(); ObjectInputStream is = new ObjectInputStream(new FileInputStream("d:\\product.txt")); Product p2 = (Product) is.readObject(); System.out.println(p2.toString()); } }