Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading all serialized objects from a file  RSS feed

 
aza chung
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see plenty of sample codes that all look similar this...

This works fine, but what if I wanted to read all the serialized objects in the file and didn't know how many objects were in there?
I'm thinking maybe a while loop that reads each object (same type, of course) in the file. Then putting to read every object. Although, I'm not sure if readObject reads subsequent objects-- I could never find a way to make that work.
If someone can help, I would appreciate it.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Unforturnately the ObjectInputStream API doesn't offer a good way to find out how many objects are available to be deserialized - so there's no way to know when to stop the loop, other than catching an exception:

This is extremely ugly, IMO. It would be somewhat better if we named the specific type of exception thrown in this case (I'm not sure and am too lazy to test it) but it's still ugly. A cleaner solution would be to put all your objects in an ArrayList, and then serialize the List all at once. Then when you deserialize it, you only call readObject() once, and it contains all your other objects inside it.
[ October 10, 2002: Message edited by: Jim Yingst ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!