需要序列化的person类代码
package Week9;
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Person(String name, String id) {
this.name = name;
this.id = id;
}
public String toString() {
return "person[" + "name=" + name + " id=" + id + "]";
}
}
序列化的具体操作代码段
package Week9;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Seria_Person implements Serializable {
public static void main(String[] args)
throws FileNotFoundException, IOException {
Person a = new Person("Justin", "4331272000...");
ObjectOutputStream os = new ObjectOutputStream
(new FileOutputStream("G:/user.bat"));
os.writeObject(a);
os.flush();
os.close();
}
}
反序列化的具体操作代码段
package Week9;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class Deser_Person implements Serializable{
//Deserialization 反序列化
public static void main(String[] args)
throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream is = new ObjectInputStream
(new FileInputStream("G:/user.bat"));
Object obj = is.readObject();
is.close();
System.out.println(obj);
}
}