Serializable序列化和反序列化

Serializable接口:
	所谓的Serializable,就是java提供的通用数据保存和读取的接口。至于从什么地方读出来和保存到哪里去都被隐藏在函数参数的背后了。这样子,任何类型只要实现了Serializable接口,就可以被保存到文件中,或者作为数据流通过网络发送到别的地方。也可以用管道来传输到系统的其他程序中。这样子极大的简化了类的设计。只要设计一个保存一个读取功能就能解决上面说得所有问题。

	当两个进程在进行远程通信时,彼此可以发送各种类型的数据。无论是何种类型的数据,都会以二进制序列的形式在网络上传送。发送方需要把这个对象转换为字节序列,才能在网络上传送;接收方则需要把字节序列再恢复为对象。     
	把对象转换为字节序列的过程称为对象的--->序列化。     
	把字节序列恢复为对象的过程称为对象的--->反序列化。
package com.enterise.test;

import java.io.Serializable;

/**
 * 实体实现序列化接口
 * @author Always
 *
 */
public class Student implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private String name;
	private int age;

	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the age
	 */
	public int getAge() {
		return age;
	}

	/**
	 * @param age
	 *            the age to set
	 */
	public void setAge(int age) {
		this.age = age;
	}

}

package com.enterise.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
 * 将对象保存在硬盘上--读取硬盘上的对象
 * @author Always
 *
 */
public class MainActivity {
	
	public static void main(String[] args){
		
		File child = new File("e://zhou");
		if(!child.exists()){
			child.mkdirs();
		}
		
		File parent = new File(child, "student.tmd");
		Student stu = new Student("xingming",2);
		
		//将对象保存到本地的硬盘
		try {
			FileOutputStream stream = new FileOutputStream(parent);
			ObjectOutputStream outStream = new ObjectOutputStream(stream);
			outStream.writeObject(stu);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

//从硬盘中读取对象
		try {
			FileInputStream stream = new FileInputStream(parent);
			ObjectInputStream inStream = new ObjectInputStream(stream);
			int len = 0;
			byte[] by = new byte[1024];
			Student student = (Student) inStream.readObject();
			System.out.println("studn------>"+student.getName());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值