日期:2014-05-20  浏览次数:20757 次

求助ObjectInputStream用法
第一次用这个字节流 如下

Java code

import java.io.*;

class Student implements Serializable{
    private String name;
    public Student(String name){
        this.name=name;
    }
    public String getName(){
        return this.name;
    }
    public String toString(){
        return "姓名:"+this.name;
    }
}
public class MyDemo{ 
    public static void main(String[] args) throws IOException, ClassNotFoundException{
        FileOutputStream fos=new FileOutputStream("m.dat");
        ObjectOutputStream oos=new ObjectOutputStream(fos);
        oos.writeObject(new Student("ahah"));
        oos.writeObject(new Student("papa"));
        System.out.println("ok!");
        oos.close();
        fos.close();
    //    
        FileInputStream fis=new FileInputStream("m.dat");
        ObjectInputStream ois=new ObjectInputStream(fis);
        while(ois.readObject()!=null){//这一行错了,是为什么?
            Student stu1=(Student)ois.readObject();
            System.out.println(stu1);
        }
        ois.close();
        fis.close();    
    }
}


为什么结果只显示了第二个对象?
Java code

ok!
姓名:papa
Exception in thread "main" java.io.EOFException
    at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2571)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
    at MyDemo.main(MyDemo.java:27)



------解决方案--------------------
while(ois.readObject()!=null){//这一行错了,是为什么? 第一次读取了ahah
Student stu1=(Student)ois.readObject();//这次读取了papa
System.out.println(stu1);
}然后再去执行循环 while(ois.readObject //第三次读取报错。
你仔细看看这句话,里面只有两个对象,你读取了两次。第三次去读取的时候当然到达文件末端了)end of file )EOFExcepiton了。
------解决方案--------------------
改一下可以了.
Java code

public class MyDemo{ 
    public static void main(String[] args) throws IOException, ClassNotFoundException{
        FileOutputStream fos=new FileOutputStream("m.dat");
        ObjectOutputStream oos=new ObjectOutputStream(fos);
        oos.writeObject(new Student("ahah"));
        oos.writeObject(new Student("papa"));
        System.out.println("ok!");
        oos.close();
        fos.close();
    //    
        FileInputStream fis=new FileInputStream("m.dat");
        ObjectInputStream ois=new ObjectInputStream(fis);
    Student s;                    //定义Student类变量.
        while((fis.available()>0)&&(s=            //判断是否到文件尾。
                (Student)ois.readObject())!=null){
            //Student stu1=(Student)ois.readObject();    //再运行就读了下一个了。
            System.out.println(s);
        }
        ois.close();
        fis.close();    
    }
}