[JavaSE] IO stream (Object serialization) and javase serialization
Write
Get the ObjectOutputStream object. The new parameter is used to construct the target file of the FileOutputStream object.
Call the writeObject () method of the ObjectOutputStream object. Parameter: object to be saved
Call the close () method of the ObjectOutputStream object to close the stream.
At this time, an exception will be reported. NotSerialzeableException occurs because the target class does not implement the Serializable interface. This interface has no method, which is called the mark interface. A new serial number is generated after the class is changed, the error message InvalidClassException is displayed when the saved file is read.
Read
Get the ObjectInputStream object. The new parameter is used to construct the target file of the FileInputStream object.
Call the readObject () method of the ObjectInputStream object to obtain the stored data.
Import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. io. objectInputStream; import java. io. objectOutputStream; import java. io. serializable; public class ObjectStreamDemo {/*** @ param args * @ throws Exception */public static void main (String [] args) throws Exception {writeObj (); readObj ();}/*** save object * @ throws IOException * @ throws FileNotFoundException */public static void writeObj () throws Exception {ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("person. object "); oos. writeObject (new Person ("taoshihan", 100);} public static void readObj () throws Exception {ObjectInputStream ois = new ObjectInputStream (new FileInputStream ("person. object "); Person person = (Person) ois. readObject (); System. out. println (person); // outputs taoshihan: 100 }}/ *** custom class * @ author taoshihan **/class Person implements Serializable {private String name; private int age; public Person (String name, int age) {this. name = name; this. age = age ;}@ Override public String toString () {// TODO Auto-generated method stub return name + ":" + age ;}}
PHP version:
<? Phpclass Person {private $ name; private $ age; public function _ construct ($ name, $ age) {$ this-> name = $ name; $ this-> age = $ age;} public function toString () {return $ this-> name. ":". $ this-> age ;}$ personObj = serialize (new Person ("taoshihan", 100); echo $ personObj; // output O: 6: "Person ": 2: {s: 12: "Personname"; s: 9: "taoshihan"; s: 11: "Personage"; I: 100 ;} $ obj = unserialize ($ personObj); echo $ obj-> toString (); // output taoshihan: 100