Emp.java
```java
package com.day05.demo3;
import java.io.Serializable;
public class Emp implements Serializable {
private int id;
private String name;
private double salary;
public Emp(int id, String name, double salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return "Emp [id=" + id + ", name=" + name + ", salary=" + salary + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
EmpUtil.java
package com.day05.demo3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class EmpUtil {
/**
* 查询方法
* @return
* @throws IOException
* @throws FileNotFoundException
* @throws ClassNotFoundException
*/
ArrayList<Emp> emps = null;
public ArrayList<Emp> selectEmp() throws Exception {
ObjectInputStream obi = new ObjectInputStream(
new FileInputStream(
new File("emp.txt")));
ArrayList<Emp> emps = (ArrayList<Emp>)obi.readObject();
return emps;
}
/**
* 插入方法
* 1.反序列化得到集合对象,
* 2.将参数对象添加到集合中
* 3.对集合进行序列化
* @throws IOException
* @throws FileNotFoundException
*/
public boolean insertEmp(Emp emp) throws Exception {
//1.创建一个file对象
File f = new File("emp.txt");
//2.创建对象输出流
if(emps!=null) { //如果原有集合不为空
//建立对象输入流
ObjectInputStream obi = new ObjectInputStream(
new FileInputStream(
new File("emp.txt")));
//将原有的集合反序列化
ArrayList<Emp> emps = (ArrayList<Emp>)obi.readObject();
obi.close();
//在原有的集合的基础上添加新的对象
emps.add(emp);
ObjectOutputStream op = new ObjectOutputStream(
new FileOutputStream(f));
op.writeObject(emps);//将需要序列化的对象作为参数
op.close();
}
else {
//如果原有集合为空
//建立文件输出流
ObjectOutputStream op = new ObjectOutputStream(
new FileOutputStream(f));
emps = new ArrayList<Emp>();
//直接将要添加的对象添加到集合中
emps.add(emp);
//对集合进行序列化
op.writeObject(emps);//将需要序列化的对象作为参数
op.close();
}
System.out.println("对象序列化成功");
return true;
}
}
TestIo.java
package com.day05.demo3;
import java.util.ArrayList;
import java.util.Scanner;
public class TestIo {
public static void main(String[] args) {
EmpUtil empUtil=new EmpUtil();
try {
empUtil.insertEmp(new Emp(1,"zs",45));
empUtil.insertEmp(new Emp(2,"bky",33));
ArrayList<Emp> emps=empUtil.selectEmp();
System.out.println(emps.toString());
for (int i = 0; i < args.length; i++) {
System.out.println(emps.get(i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
序列化和反序列化就以这个程序为例,详细的注释希望能有所帮助。