Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EOFexception in Java when reading objectinputstream

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");
        }
like image 267
user276712 Avatar asked Jun 12 '26 18:06

user276712


1 Answers

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?

like image 134
user207421 Avatar answered Jun 14 '26 08:06

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!