import java.io.*;
import java.util.*;
class Student implements Serializable  
{                                   
String name;
int age;
public Student(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
  return name;
}
public int getAge()
{
return age;
}
public String toString()
{
   return name+" "+age;
}}public class TestObjectStream
{
public static void main(String[] args)
{
Student student [] = {
new Student("zhange",60),
new Student("zhansf",61),
new Student("zhagsg",62),
new Student("zangsh",63),
new Student("zfangi",65),
new Student("zhangg",66),
new Student("zhanga",67),
new Student("zhangb",68),
new Student("zhangc",69),
new Student("zhangd",70),
};
 
try{
      File f=new File("f://haifei.txt");      ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));for (int i = 0;i<student.length ;i++ )
{
 oos.writeObject(student[i]);//写十个学生对象
}
           oos.close();

     
ObjectInputStream ois=new ObjectInputStream(new FileInputStream(f));


Object a = ois.readObject();
while (ois!=null)
{
System.out.println(a);
ois.close();
break;

}

      
      
}
catch(Exception e){
      e.printStackTrace();
}
}
}为什么我读的时候只读出了一行...

解决方案 »

  1.   

    Object a;
    try{
    while(true){
    a=ois.readObject();
    System.out.println(a);
    }
    }
    catch(Exception e){
    ois.close();
    }
    可以读出所有的对象,在循环中读取对象,并利用异常结束循环
      

  2.   

    这个可以读出所有对象了
    但最后抛出了异常..
    请问那异常信息是什么意思
    java.io.EOFException我应该怎么处理才可以不让他打印这种异常信息...
      

  3.   

    java.io.EOFException是因为意外地到达文件尾或流尾。那个while(true)该成for也行啊,你不就写入了10个对象嘛。可以把所有要写入的对象放入一个容器里,再写那个容器,我一般是那么做的。
      

  4.   

    if (ois!=null){
    Object a;
    while((a= ois.readObject())!=null)
    {
    System.out.println(a);
    }
    ois.close();
    }
         
    }
    catch(EOFException e){
          System.out.println("文件读取完毕");//处理里这步后跳出try块继续执行
    }
    catch(Exception e){
    }