package com.cissst.software.model;
/*
* 1.用对象序列化实现将多名员工对象保存在集合中,然后将集合保存在文件中。
* 然后在实现反序列化操作,在控制台中输出集合中的员工对象.
*
*/
public class Employee {
//员工姓名
private String employeeName;
//员工编号
private String employeeId;
//员工年龄
private int age;
public Employee() {
super();
// TODO Auto-generated constructor stub
}
public Employee(String employeeName, String employeeId, int age) {
super();
this.employeeName = employeeName;
this.employeeId = employeeId;
this.age = age;
}
@Override
public String toString() {
return "Employee [employeeName=" + employeeName + ", employeeId="
+ employeeId + ", age=" + age + "]";
}
}
package com.cissst.software.test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import com.cissst.software.model.Employee;
/*
* 实现序列化与反序列化操作
* Serializable
* 写员工信息
*/
public class Test1 implements Serializable{
@Test
public void testMethod1() throws IOException{
//创建员工对象
Employee employee = new Employee("张三","01",20);
//将员工信息保存到文件中
OutputStream os = new FileOutputStream("temp.txt");
//创建对象输出流
ObjectOutputStream out = new ObjectOutputStream(os);
//保存员工对象
out.writeObject(employee);
//关闭输出流
out.close();
os.close();
}
/*
* 反序列化操作
*/
// @Test
// public void testMethod2() throws Exception{
// //创建输入流对象
// InputStream is = new FileInputStream("temp.txt");
// //创建对象输入流
// ObjectInputStream in = new ObjectInputStream(is);
// //读取员工对象
// Employee employee = (Employee) in.readObject();
// System.out.println(employee);
// //关闭输入流
// in.close();
// is.close();
// }
//
/*
* 反序列化操作
* 读员工信息
*/
@Test
public void testMethod3() throws Exception{
//创建输入流对象
InputStream is = new FileInputStream("temp.txt");
//创建对象输入流
ObjectInputStream in = new ObjectInputStream(is);
//创建3个员工对象
Employee employee1 = new Employee("张三","01",20);
Employee employee2 = new Employee("李四","02",22);
Employee employee3 = new Employee("王五","03",23);
//创建一个容器(集合)
Set students = new HashSet();
//将学生对象添加到集合中
students.add(employee1);
students.add(employee2);
students.add(employee3);
//读取员工对象
System.out.println(students);
//关闭输入流
in.close();
is.close();
}
}