package com.lxht.test;
import java.io.*;
public class TestSerial {
public static void main(String[] args) {
SerialObject seObject = new SerialObject();
seObject.setAge("2" );
seObject.setClassName("1年3班" );
seObject.setName("张三" );
try {
System.out .println(seObject);
FileOutputStream fos = new FileOutputStream(new File("cc.obj" ));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(seObject);
oos.close();
fos.close();
FileInputStream fis = new FileInputStream(new File("cc.obj" ));
ObjectInputStream ois = new ObjectInputStream(fis);
SerialObject tmpObj = (SerialObject)ois.readObject();
System.out .println(tmpObj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class SerialObject implements Serializable {
private transient String age ; //该类变量不会被序列号
private String name ;
private String className ;
public String getAge() {
return age ;
}
public void setAge(String age) {
this .age = age;
}
public String getName() {
return name ;
}
public void setName(String name) {
this .name = name;
}
public String getClassName() {
return className ;
}
public void setClassName(String className) {
this .className = className;
}
/**
* ObjectOutputStream在调用writeObject方法时,
* writeObject中会判断是否有writeReplace(),如果有,则用writeReplace()获取到的Object做替换
* @return
* @throws ObjectStreamException
*/
public Object writeReplace() throws ObjectStreamException{
SerialObject writeObj = new SerialObject();
writeObj.setName("王五" );
return writeObj;
}
/**
* ObjectOutputStream在调用readObject方法时,
* readObject中会判断是否有readResolve(),如果有,则用readResolve获取到的Object做替换
* @return
* @throws ObjectStreamException
*/
public Object readResolve() throws ObjectStreamException{
SerialObject cc = new SerialObject();
cc.setClassName("李四" );
return cc;
}
@Override
public String toString() {
String objStr = this .getName() + ";" + this .className + ";" + this .age ;
return objStr;
}
}