The serialization of objects in Java classes is done through ObjectOutputStream and ObjectInputStream.
Write:
1File afile=NewFile ("E:\\c.txt");2Stu a=NewStu (1, "AA", "1");3FileOutputStream fileoutputstream=NULL;4 Try {5FileOutputStream =NewFileOutputStream (afile);6ObjectOutputStream objectoutputstream=NewObjectOutputStream (fileoutputstream);7 Objectoutputstream.writeobject (a);8 Objectoutputstream.flush ();9 objectoutputstream.close ();Ten}Catch(FileNotFoundException e) { One //TODO auto-generated Catch block A e.printstacktrace (); -}Catch(IOException e) { - //TODO auto-generated Catch block the e.printstacktrace (); -}finally { - if(fileoutputstream!=NULL) - { + Try { - fileoutputstream.close (); +}Catch(IOException e) { A //TODO auto-generated Catch block at e.printstacktrace (); - } - } -}
Read:
1 fileinputstream fileinputstream=new FileInputStream (afile); 2 ObjectInputStream objectinputstream=New ObjectInputStream (fileinputstream); 3 Stu s=(Stu) objectinputstream.readobject (); 4 System.out.println (s);
Attention:
For any object that needs to be serialized, it must implement the interface serializable, which is simply an identity interface that itself does not have any members, but is used to identify objects that illustrate the current implementation class can be serialized.
If you have some properties in your class that you want to not serialize during object serialization, you can use the keyword transient callout adornment. When an object is serialized, the member property labeled transient is automatically skipped. If a serializable object contains a reference to a non-serializable object, the serialization operation fails and throws a Notserializableexception exception, so the reference tag is transient and can be serialized.
When an object is serialized, only non-static member variables of the object are saved, and no member methods, static member variables, are saved.
If the member variable of an object is an object, then the data members of the object will be saved and restored, and will be recursive.
Java writes an object to a file read-serialization and deserialization