Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to detect end of file

 
tan kian
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Pie
Posts: 9259
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a few minutes and become familiar with the Java API documentation for java.io.ObjectInputStream. 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.
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic