Student.java package com.io; import java.io.IOException; import java.io.RandomAccessFile; import java.io.Serializable; public final class Student implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int num; private String name; private transient double score; public Student() { } public Student(int num, String name, double score) { super(); this.num = num; this.name = name; this.score = score; } @Override public String toString() { return num + ":" + name + ":" + score; } public void writeStudent(RandomAccessFile raf) throws IOException { raf.writeInt(num); raf.writeUTF(name); raf.writeDouble(score); } public void readStudent(RandomAccessFile raf) throws IOException { num = raf.readInt(); name = raf.readUTF(); score = raf.readDouble(); } /*private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeInt(num); out.writeUTF(name); // 证实是否真的调用了该方法 System.out.println("writeObject()"); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { num = in.readInt(); name = in.readUTF(); // 证实是否真的调用了该方法 System.out.println("readObject()"); }*/ } SerializableTest.java package com.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; public class SerializableTest { public static void main(String[] args) throws Exception { Student s1 = new Student(10, "张三", 50); Student s2 = new Student(21, "李四", 60); Student s3 = new Student(34, "王五", 70); ArrayList<Student> al = new ArrayList<Student>(); al.add(s1); al.add(s2); al.add(s3); ser(al); al = dser(); for (int i = 0; i < al.size(); i++) { Student st = (Student) al.get(i); System.out.println(st); } // 构造对象输出流 /* * FileOutputStream fos = new * FileOutputStream("G:/root/a.txt"); ObjectOutputStream oos = new * ObjectOutputStream(fos); oos.writeObject(s1); oos.writeObject(s2); * oos.writeObject(s3); oos.close(); * * // 构造对象输入流 FileInputStream fis = new * FileInputStream("G:/root/a.txt"); ObjectInputStream ois = new * ObjectInputStream(fis); Student s; for (int i = 0; i < 3; i++) { s = * (Student) ois.readObject(); System.out.println(s);// 打印雇员信息 } * ois.close(); */ } public static void ser(ArrayList<Student> al) throws Exception { File f = new File("G:/root/a.txt"); FileOutputStream fos = new FileOutputStream(f); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(al); oos.close(); } @SuppressWarnings("unchecked") public static ArrayList<Student> dser() throws Exception { File f = new File("G:/root/a.txt"); FileInputStream fis = new FileInputStream(f); ObjectInputStream ois = new ObjectInputStream(fis); ArrayList<Student> al = (ArrayList<Student>) ois.readObject(); ois.close(); return al; } }