3

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");
        }
4
  • 1
    If you get an EOFException, it's probably because you've reached the end of the file. Commented Feb 22, 2010 at 0:39
  • yes, i assume it's reaching the end of the file. Commented Feb 22, 2010 at 0:42
  • 1
    I've tried this and I only ever get EOFException. Under what circumstances do you get NullPointerException? Commented Feb 22, 2010 at 1:18
  • Possible duplicate of stackoverflow.com/questions/18451232/… Commented Mar 25, 2016 at 17:30

1 Answer 1

6

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?

Sign up to request clarification or add additional context in comments.

2 Comments

How do you solve the EOFException problem? Should I wrap the code in a try/catch block and wait for the exception to arise>
It's not a 'problem', it's an exception. Catch it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.