package demo;
import java.io.File;
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.OutputStream;
import java.io.Serializable;
public class SerializeDemo {
private static final File SAVE_FILE=new File("D:"+File.separator+"save.person");
public static void main(String[] args) throws Exception {
//序列化,指将对象转化为二进制,用来保存/网络传输
//序列化(ObjectOutputStream,writeObject)与反序列化(ObjectInputStream,readObject)
//transient关键字,使得变量不做序列化(取默认值)
saveObject(new Person("赵二三", 23));
System.out.println(loadObject());
}
public static void saveObject(Object obj) throws Exception {
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(SAVE_FILE) );
oos.writeObject(obj);
oos.close();
}
public static Object loadObject() throws Exception {
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(SAVE_FILE) );
Object obj=ois.readObject();
ois.close();
return obj;
}
}
@SuppressWarnings("serial")
class Person implements Serializable{ //实现Serializable接口,使得Person类可以被序列化
private String name;
private int age;
public Person(String name,int age) {
this.name=name;
this.age=age;
}
public String toString() {
return "姓名:"+this.name+" , 年龄:"+this.age;
}
}