话说JAVA SE 序列化(serializable)与 外部化(externalizable)简单实例

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;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值