One: serialization of Objects
Object serialization is a way to turn an object into a binary data stream.
In order for a class to be serialized, the Java.io.Serializable interface must be implemented. Although there is no method in this interface, it is just like the previous cloneable interface. Once this interface is implemented, it indicates that the class has the ability to be serialized.
/** * Implementation of class with serialization capability * */public class Serializabledemo implements serializable{public Serializabledemo () { } public seria Lizabledemo (string name, int age) {this.name=name; this.age=age;} @Override public String toString () {return name: "+name+" Age: "+age; } private String name; private int age;}
/** * Implements a class with serialization capability * */public class Person implements serializable{public person () {} public person (String name, I NT age) {this.name = name; this.age = age;} @Override public String toString () {return ' name: ' + name + ' Age: ' + ages;} private String name; private int age;} /** * Demonstration ObjectOutputStream * */public class objectoutputstreamdemo{public static void Main (string[] args) throws Ioexcept ion{File File = new file ("D:" + File.separator + "Hello.txt"); ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (file)); Oos.writeobject (New person ("Rollen", 20)); Oos.close (); }}
When we look at the resulting hello.txt, we see garbled characters. Because it is a binary file.
Although we cannot view the contents directly, we can use the ObjectInputStream class to view:
/** * ObjectInputStream Demonstration * */public class objectinputstreamdemo{public static void Main (string[] args) throws exception{ File File = new file ("D:" + File.separator + "Hello.txt"); ObjectInputStream input = new ObjectInputStream (new FileInputStream (file)); Object obj = Input.readobject (); Input.close (); System.out.println (obj); }}
Result: Name: Rollen Age: 20
What exactly is serialized?
In fact, only attributes are serialized.
Java io finishing (bottom)