import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.Externalizable;
import java.io.ObjectInput;
import java.io.ObjectOutput;
//自己控制序列化的过程中,被序列化的类必须有一个无参的构造方法,否则将出现(java.io.InvalidClassException)异常
public class TestObjectSerializable {
public static void main(String [] args) {
Persion p = new Persion("xxxx",24,"man");
try{
FileOutputStream fos = new FileOutputStream("d:/meteor/serable.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p);
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream("d:/meteor/serable.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Persion per = (Persion)ois.readObject();
System.out.println(per);
ois.close();
}catch(FileNotFoundException fe){
System.out.println("所指定文件不是有效,或者它是一个目录");
System.exit(-1);
}catch(ClassNotFoundException ce){
ce.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
/*
class Persion implements Externalizable {
private String name;
private int age;
private String sex;
public Persion(String name,int age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
public Persion() {};
public String toString(){
return "姓名:" + this.name + " 年龄:" + this.age + " 性别:" + this.sex;
}
public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException{
this.name = in.readUTF();
this.age = in.readInt();
//this.sex = in.readUTF();
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(this.name);
out.writeInt(this.age);
//out.writeUTF(this.sex);
}
}
*/
class Persion implements Serializable {
private String name;
private int age;
private transient String sex;
public Persion(String name,int age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
public String toString(){
return "姓名:" + this.name + " 年龄:" + this.age + " 性别:" + this.sex;
}
}
话说JAVA SE 序列化(serializable)与 外部化(externalizable)简单实例
最新推荐文章于 2021-02-24 20:21:56 发布