Serialization and deserialization of objects

Person_ Class 1:

import java. io. Serializable; public class Person_ 1 implements Serializable { private String name; private int age; public Person_1(String name,int age) { super(); this.name = name; this.age = age; } public Person_ 1() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @ Override public String toString() { return "Person [name=" + name + ",age=" + age + "]"; }

}

Demo class:

import java. io. FileInputStream; import java. io. FileOutputStream; import java. io. IOException; import java. io. ObjectInputStream; import java. io. ObjectOutputStream; /* * IO stream object to serialize and deserialize the object person * objectoutputstream write object to serialize * objectinputstream read object to deserialize * / public class objectstream {public static void main (string [] args) throws IOException, classnotfoundexception {function_1();} / ** Objectoutputstream * construction method: objectoutputstream (OutputStream out) * pass any byte output stream * void writeobject (object obj) write out the object * / public static void function () throws IOException {/ / create a byte output stream and encapsulate the file fileoutputstream FOS = new fileoutputstream ("D: \ \ demo \ \ a.txt") ; // Create an object that writes out the serialized stream of the object, and the constructor passes the byte output stream objectoutputstream OOS = new objectoutputstream (FOS); Person_ 1 p=new Person_ 1("lisi",25); // Call the method writeobject of the serialized stream to write out the object OOS writeObject(p); oos. close(); } /* * Objectinputstream * construction method: objectinputstream (InputStream in) * pass any byte input stream. The input stream encapsulates the file and must be a serialized file * object readobject() reads the object * / public static void function_ 1) throws IOException, classnotfoundexception {FileInputStream FIS = new FileInputStream ("D: \ \ demo \ \ a.txt"); / / create a deserialized stream and construct a method to pass the byte input stream objectinputstream OIS = new objectinputstream (FIS); / / call the method of deserializing the stream readobject() to read the object obj = OIS. Readobject(); system. Out. Println (obj); OIS. Close();}}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>