Java 序列化 serializable

本文介绍了一个Java中实现对象序列化的具体示例。通过定义一个包含姓名、年龄和部门属性的Employee类,并实现了Serializable接口,使该类的对象能够被序列化为二进制流。此外,还提供了将Employee对象写入文件以及从文件读取对象的两个示例程序。
package serializable;

import java.io.Serializable;
/**
 * 实现具有序列化能力的类(把对象变为二进制数据流)
 * implements Serializable
 */
public class Employee implements Serializable {
	private static final long serialVersionUID = 1L;
	private String name; 
	private int age;
	private String dept;

	//public Employee(){}
	public Employee(String name,int age,String dept){
		this.name = name;
		this.age = age;
		this.dept = dept;
	}
	public String getName(){
		return name;	
	}
	public void setAge(int age){
		this.age = age;	
	}
	public int getAge(){
		return age;	
	}
	public void setDept(String dept){
		this.dept = dept;	
	}
	public String getDept(){
		return dept;	
	}
	public void showInfo(){
		System.out.println("name:" + name + "\tage:" + age + "\tdept:" + dept);
	}
}

package serializable;

import java.io.*;

public class WriteObject {
	public static void main(String[] args) {
		try {
			FileOutputStream fos ;
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.ser"));
			oos.writeObject(new Employee("张三", 28, "市场部"));
			oos.writeObject(new Employee("李四", 34, "技术部"));
			oos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
package serializable;

import java.io.*;

public class ReadObject {
	public static void main(String[] args) {
		try {
			FileInputStream fis ;
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser"));
			
			Employee e1 = (Employee) ois.readObject();
			Employee e2 = (Employee) ois.readObject();

			e1.showInfo();
			e2.showInfo();
			ois.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值