package com.duoduo.day321;
//外部序列化实现
import java.io.Externalizable;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.sql.Date;
import java.text.SimpleDateFormat;
public class Person3 implements Externalizable {
private static final long serialVersionUID=2L;
private String name;
private transient int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//写操作
public void writeExternal(ObjectOutput out) throws IOException{
out.writeObject(this.name);
out.writeObject(this.age);
System.out.println(this);
System.out.println("序列化成功");
}
//读操作
public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException{
this.name=(String)in.readObject();
this.age=(Integer) in.readObject()-2;
//SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM--dd");
//Date date=(Date) in.readObject();
//System.out.println("反序列化的日期为"+sdf.format(date));
System.out.println("反序列化成功");
System.out.println(this);
}
public String toString() {
return "Person3:name="+name+";age="+age;
}
//测试代码
public static void main(String [] args) {
//写入(序列化)
Person3 p3=new Person3();
p3.setName("dandan");
p3.setAge(90);
try {
FileOutputStream fos=new FileOutputStream("D:\\Java\\demo\\day321\\p3.txt");
ObjectOutputStream os=new ObjectOutputStream(fos);
os.writeObject(p3);
fos.close();
os.close();
}catch(Exception ex) {
ex.printStackTrace();}
try { //读取(反序列化)
FileInputStream fis=new FileInputStream("D:\\Java\\demo\\day321\\p3.txt");
ObjectInputStream is=new ObjectInputStream(fis);
is.readObject();
fis.close();
is.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
![](//img-blog.csdn.net/20180321210010670?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L2R1b2R1bzE4dXA=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
![](//img-blog.csdn.net/20180321210242457?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L2R1b2R1bzE4dXA=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)