【慕课笔记】6-1 序列化基本操作

6-1 序列化基本操作


1、对象序列化,就是将Object转换成byte序列,反之叫对象的反序列化

2、序列化流(ObjectOutputStream),是过滤流----writeObject

     反序列化流(ObjectInputStream)----readObject

3、序列化接口(Serializable) 

对象必须实现序列化接口,才能进行序列化,否则将出现异常

这个接口,没有任何方法,只是一个标准


import java.io.Serializable;

public class Student implements Serializable{
	private String stuno;
	private String stuname;
	private int stuage;
	
	public Student(){
		
	}
	
	
	public Student(String stuno, String stuname, int stuage) {
		super();
		this.stuno = stuno;
		this.stuname = stuname;
		this.stuage = stuage;
	}


	public String getStuno() {
		return stuno;
	}
	public void setStuno(String stuno) {
		this.stuno = stuno;
	}
	public String getStuname() {
		return stuname;
	}
	public void setStuname(String stuname) {
		this.stuname = stuname;
	}
	public int getStuage() {
		return stuage;
	}
	public void setStuage(int stuage) {
		this.stuage = stuage;
	}


	@Override
	public String toString() {
		return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage="
				+ stuage + "]";
	}
	
	
}


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws ClassNotFoundException 
	 */
	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		String file="demo/obj.dat";
		//1.对象的序列化(应用于网络传输)
//		ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file));
//		Student stu=new Student("1","alice",12);
//		oos.writeObject(stu);
//		oos.flush();
//		oos.close();
		
		//2.反序列化
		ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
		Student stu=(Student)ois.readObject();
		System.out.println(stu);
		ois.close();

	}

}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值