- import java.io.*;
- import java.util.*;
- //定义学生类
- class Student implements Serializable
- {
- public static final long serialVersionUID = 42L;
- //自己定义UID,保证UID唯一
- private String name;
- private int age;
- Student(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public String toString()
- {
- return name+":"+age;
- }
- }
复制代码- //添加对象
- public static void writeObj()throws IOException
- {
- ObjectOutputStream oos=
- new ObjectOutputStream(new FileOutputStream("C:\\obj.txt"));
- oos.writeObject(new Student("wangwu",23));
- oos.writeObject(new Student("lisi",25));
- oos.close();
- }
复制代码- public static void readObj()throws Exception
- {
- ObjectInputStream ois=new ObjectInputStream(new FileInputStream("C:\\obj.txt"));
- //循环读取
- Object obj=null;
- try
- {
- while ((obj=ois.readObject())!=null)
- {
- Student stu=(Student)ois.readObject();
- System.out.println(stu);
- }
- }
- catch (EOFException e)
- {
- System.out.println("到达文件结尾");
- }
- }
复制代码数据都读出来了,但是抛出了EOFException。
请教这个异常要处理么,该怎么处理啊?