Serialization and deserialization processing
With the serialization support class, if you want to implement serialization and deserialization operations, you can use the following two classes to complete:
Class name | Serialization: ObjectOutputSteam | Deserialization: ObjectIntputStream |
Class definition | public class ObjectOutputStream extends OutputStream implements ObjectOutput, ObjectStreamConstants |
public class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants |
Construction method | public ObjectOutputStream(OutputStream out) throws IOException |
public ObjectInputStream(InputStream in) throws IOException |
Operation method | public final void writeObject(Object obj) throws IOException |
public final Object readObject() throws IOException, ClassNotFoundException |
Example: Realize serialization and deserialization
package 序列化;
import java.io.*;
public class 序列化的基本概念{
private static final File SAVE_FILE = new File("D:\\Test\\person.person");
public static void main(String[] args) throws Exception{
//序列化,完成后生成person.person文件
saveObject(new Person("张三",18));
//反序列化
System.out.println(loadObject());
}
public static void saveObject(Object obj) throws Exception{
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(SAVE_FILE));
objectOutputStream.writeObject(obj); //序列化
objectOutputStream.close();
}
public static Object loadObject() throws Exception{
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(SAVE_FILE));
Object obj = objectInputStream.readObject(); //反序列化
objectInputStream.close();
return obj;
}
}
class Person implements Serializable{ //Person类可以被序列化
private String name;
private int age;
public Person(String name,int age){
this.name = name ;
this.age = age;
}
@Override
public String toString(){
return "姓名:"+this.name+"、年龄:"+this.age;
}
}
Name: Zhang San, age: 18
Serialization and deserialization in java must use the internally provided object operation flow, because it involves the format of binary data, so you can’t customize the processing. If you want to achieve serialization of a set of pairs, you can use The object array is complete.
In the development process of many actual projects, developers can see these two classes more or less, because many containers help developers automatically implement them.