3.Java核心API---序列化

1.为什么要序列化

在开发中,经常需要将对象的信息保存到磁盘中以便于以后检索。如果逐一的对对象的属性进行操作通常是非常繁琐的,而且容易出错。简单的说,序列化就是将对象的状态存储到特定的存储介质中的过程,也就是将对象状态转换为可保持或可传输的过程。其实,就是把对象转换为流,写入到文件中。反序列化就是把写入文件的内容读取出来。

2.实例

package IO;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Student implements Serializable {
	String name;
	String age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

}

public class Serial_ext {
	public static void main(String[] args) {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream("E:\\stu.txt"));
			Student stu = new Student();
			stu.setName("李白");
			stu.setAge("20");
			oos.writeObject(stu);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}
}


clip_image002

package IO;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class Serial_get {
	public static void main(String[] args) throws ClassNotFoundException {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream("E:\\stu.txt"));
			Student stu = (Student) ois.readObject();
			System.out.println("学生姓名:" + stu.getName());
			System.out.println("学生年龄:" + stu.getAge());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


clip_image004

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值