The object is serialized to save the object to a disk or transmit it over the network. The object serialization mechanism allows the conversion layer of java objects in memory to binary streams unrelated to the platform. If an object is to be serialized, it must inherit the Serializable or Externalizable interfaces. Once these two interfaces are inherited, such objects can be serialized, in addition, each object will be serialized once in the java serialization mechanism. If another class object is referenced in an object, the object of this class will also be serialized, therefore, you must ensure that this class is also a serializable class. However, if you want to disable the serialization of a field in a class, you can add the key word transient in the field declaration step 1. create an ObjectOutputStream to process the stream 2. call the method writeObject () to output the serializable object.
try { ObjectOutputStream obj = new ObjectOutputStream( new FileOutputStream("1.txt")); Pserson pe=new Pserson("xiong", 23); obj.writeObject(pe); } catch (Exception e) { e.printStackTrace(); }
If you want to restore a Java object, deserialization is required. During deserialization, the basic steps must be read in the write order: 1. create an ObectInputStream to process the stream 2. call its method readObject () to read objects in the stream
ObjectInputStream obj = new ObjectInputStream(new FileInputStream( "1.txt")); Pserson pe = (Pserson) obj.readObject(); System.out.println("name:" + pe.getName() + " age:" + pe.getAge());