File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes how to detect end of file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "how to detect end of file" Watch "how to detect end of file" New topic

how to detect end of file

tan kian
Ranch Hand

Joined: Apr 24, 2006
Posts: 30
hi all, the code below only reads from halfway through the file, and at the end it throws an EOFException. i thought that "while (os.readObject() != null)" would prevent this, but apparently i need to use something else. can someone help? thanks.

Joe Ess

Joined: Oct 29, 2001
Posts: 9189

Take a few minutes and become familiar with the Java API documentation for You will see that readObject() does not return null on EOF, it throws various exceptions.
I am not a fan of using exceptions to report expected conditions like EOF, so I recommend that if you are going to store an unknown number of objects, store them in a Collection of some sort and serialize that. Then you can read the all the objects in with a single call and an exception will indicate an exceptional condition.

[How To Ask Questions On JavaRanch]
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
Basically you are reading from the underlaying stream twice.

When you do os.readObject() you read an object from the underlaying ObjectInputStream, but you actually do not store this reference in any variable.

If this object you are reading is the last object in the stream, then, when you call os.readObject() on the stream again then you get an IOException

You need to know how many object there are in the stream so that you do not commit this error.

Let's say you have to serialize the items in a List. You have to do somewhat like this:

And to deserialize it:

I hope this helps!
[ May 09, 2006: Message edited by: Edwin Dalorzo ]
tan kian
Ranch Hand

Joined: Apr 24, 2006
Posts: 30
every topic i searched on replied to the poster that he is reading it twice. i didnt know y before, but now i know the reason. =) thanks guys!!!
I agree. Here's the link:
subject: how to detect end of file
It's not a secret anymore!