繁体   English   中英

不确定为什么我会收到 EOFException

[英]Not sure why I'm getting an EOFException

我正在尝试从我写入的文件中读取对象,但在读取时会抛出 EOFException。 我可以看到它读取了对象,但是在读取文件的中途出现了错误。

public class IOStream {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ClassNotFoundException {

        Person[] people = new Person[14];
        people[0] = new Professor("Professor", "Issac", "Newton", "Physcis", 6);
        people[1] = new TA("TA", "Marie", "Curie", "Physics", 6);
        people[2] = new Professor("Professor", "Issac", "Newton", "Calculus", 4);
        people[3] = new Student("Student", "Amy", "Adams", "Calculus", 4);
        people[4] = new Student("Student", "Will", "Smith", "Calculus", 4);
        people[5] = new Student("Student", "Brad", "Pitt", "Physics", 6);
        people[6] = new Student("Student", "Will", "Smith", "Physics", 6);
        people[7] = new Professor("Professor", "Dimitri", "Mendeleev", "Chemistry", 6);
        people[8] = new TA("TA", "Carl", "Gauss", "Calculus", 4);
        people[9] = new Student("Student", "Amy", "Adams", "Economics", 3);
        people[10] = new Professor("Professor", "Adam", "Smith", "Economics", 3);
        people[11] = new TA("TA", "Marie", "Curie", "Chemistry", 6);
        people[12] = new Student("Student", "Brad", "Pitt", "Chemistry", 6);
        people[13] = new Student("Student", "Will", "Smith", "Chemistry", 6);

        //WRITING
        try ( ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream (new FileOutputStream("object.txt")))) {
            for (int i = 0; i < people.length; i++) {
                out.writeObject(people[i]);
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        try (ObjectInputStream in = new ObjectInputStream(new BufferedInputStream( new FileInputStream("object.txt")))){
            
            
            Person lol;
            while ((lol = (Person)in.readObject())!= null){
                System.out.println(lol);
            }
        }
        catch(EOFException i){
            i.printStackTrace();
            System.out.println("End of File");
        }
        catch (IOException e){
            e.printStackTrace();
        } 
    }
}

你得到一个EOFException因为你已经到达了文件的结尾

出于某种原因,您假设in.readObject()在到达输入末尾时将返回null ,但这不是指定的方式。

可以只使用EOFException作为流程控制(即让它在正常操作的流程中发生)或更改为您不必猜测是否有更多对象可用的格式。 做第二件事的最简单方法是只写整个数组而不是单个人:

用 just 替换你的写作循环

out.writeObject(people);

你的阅读循环是这样的:

Person[] readPeople = (Person[]) in.readObject();
for (int i = 0; i < readPeople .length; i++) {
    System.out.println(readPeople[i]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM