• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

how to detect end of file  RSS feed

 
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.

 
Bartender
Posts: 9550
12
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.
 
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
Boost this thread!