序列化的步骤:

  1. 实现Serrializable接口
  2. 创建对象输出流
  3. 调用writeObject()方法将对象写入文件
  4. 关闭对象输出流

注意:使用集合保存对象,可以将集合中的所有对象序列化.

序列化以及反序列化测试:
student类:

public class Student implements java.io.Serializable {
	private static final long serialVersionUID = 1L;// 记录版本信息
	private String name;
	private int age;
	transient private String gender;//对gender属性不序列化

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

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

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

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}
}

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class SerializableDemo {

	public static void main(String[] args) {
		// 1.创建一个需要序列化的学生对象
		Student stu = new Student("小Hudie", 18, "男");
		// 2.创建一个对象输出流
		OutputStream os = null;
		ObjectOutputStream oos = null;

		// 3.创建对象输入流
		FileInputStream is = null;
		ObjectInputStream ois = null;
		try {
			os = new FileOutputStream("f:/student.bin");
			oos = new ObjectOutputStream(os);
			oos.writeObject(stu);

			is = new FileInputStream("f:/student.bin");
			ois = new ObjectInputStream(is);
			Student stu2 = (Student) ois.readObject();
			System.out.println("个人介绍:" + stu2.getName() + "," + stu2.getAge() + "," + stu2.getGender());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException 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();
				}
			}
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (os != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

序列化后文件存储在f:/student.bin: