EOFexception in Java when reading objectinputstream

人走茶凉 提交于 2019-12-08 08:06:00

问题


I want to read multiple objects (my own class Term) that I have output to a .dat file, but I always get a nullPointException or EOFException.

ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(masterFile));
        Object o = null;
        while(( o = inputStream.readObject()) != null){
            Term t = (Term)o;
            System.out.println("I found a term");
        }

回答1:


See the Javadoc. readObject() doesn't return null at EOF. It throws EOFException. The only way it can return a null is if you wrote a null at the other end, and that's not necessarily a good reason for terminating the read loop.

In short your code is wrong.

NB the initialization of 'o' is redundant.

NB (2) The code you posted cannot throw NullPointerException, unless masterFile is null. Is that a serious report or just a guess?



来源:https://stackoverflow.com/questions/2308128/eofexception-in-java-when-reading-objectinputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!