import java.io.Serializable;
public class Employee implements Serializable {/**
*
*/
private static final long serialVersionUID =1L;
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck(){
System.out.println("Mailing a check to "+ name +" "+ address);}}
序列化
import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;publicclassSerializeDemo{publicstaticvoidmain(String[] args){
Employee e =newEmployee();
e.name ="Reyan Ali";
e.address ="Phokka Kuan, Ambehta Peer";
e.SSN =11122333;
e.number =101;try{// 获取文件输出流
FileOutputStream fileOut =newFileOutputStream("./employee.ser");// 将文件输出流加工成对象输出流
ObjectOutputStream out =newObjectOutputStream(fileOut);// 向对象输出流中写入特定的对象实例
out.writeObject(e);// 关闭对象输出流
out.close();// 关闭文件输出流
fileOut.close();
System.out.println("Serialized data is saved in ./employee.ser");}catch(IOException i){
i.printStackTrace();}}}
反序列化
import java.io.FileInputStream;import java.io.ObjectInputStream;publicclassDeserializeDemo{publicstaticvoidmain(String[] args){
Employee e = null;try{
FileInputStream fileIn =newFileInputStream("./employee.ser");
ObjectInputStream in =newObjectInputStream(fileIn);
e =(Employee) in.readObject();
in.close();
fileIn.close();}catch(ClassNotFoundException c){
System.out.println("Employee class not found");
c.printStackTrace();return;}catch(Exception i){
i.printStackTrace();return;}
System.out.println("Deserialized Employee...");
System.out.println("Name: "+ e.name);
System.out.println("Address: "+ e.address);
System.out.println("SSN: "+ e.SSN);
System.out.println("Number: "+ e.number);}}