package com.JavaIOMytest;
import java.io.*;
public class Person implements Serializable {/*对象继承自Serializable*/
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;
}
}
package com.JavaIOMytest;
import java.io.*;
public class SerializableDemo {
public static void main(String[] args) throws Exception {
File f=new File("SerializedPerson");
serialize(f);
deserialize(f);
}
public static void serialize(File f)throws Exception{/*对象序列化*/
OutputStream outputFile=new FileOutputStream(f);
ObjectOutputStream cout=new ObjectOutputStream(outputFile);
cout.writeObject(new Person("张三",25));
cout.close();
}
public static void deserialize(File f)throws Exception{/*对象反序列化*/
InputStream inputFile=new FileInputStream(f);
ObjectInputStream cin=new ObjectInputStream(inputFile);
Person p=(Person)cin.readObject();/*从文件中读入内容,之后将读入 的内容转型为 Person 类的实例*/
System.out.println(p);/*行直接打印 Person 对象实例,在打印对象 时,默认调用 Person 类中的 toString()方法*/
}
}