When deserializing in Java, how do you know if there is more objects left?

DWW

Platinum Member
Apr 4, 2003
2,030
0
0
I'm curious how you tell if there are objects left in a stream when you are deserializing objects.

is the .available() method the only way? it indicates bytes but I guess if bytes is > 0 then there should be data left for sure eh?

Only one data type is being serialized and put into the same file (many of them) but I don't know how many and must deserialize.
 

DWW

Platinum Member
Apr 4, 2003
2,030
0
0
Hrm I'm not sure if available will work... I tried it and it said I had 0 bytes in the file when clearly there was a serialized object.

I'm thinking since I don't know the exact number of objects serialized perhaps it is best to use something like a collection then serialize it... that way all references the collection makes also get serialized and to read the objects and deserialize its as easy as one readObject?

thoughts anyone?
 

DWW

Platinum Member
Apr 4, 2003
2,030
0
0
Originally posted by: Templeton
the readObject method should return null when there's nothing left to read.

hrm I have the available() way working now but is it a poor design? I'm thinking that doing a while readObject != null is the better of the two?
 

Templeton

Senior member
Oct 9, 1999
467
0
0
Originally posted by: DWW
Originally posted by: Templeton
the readObject method should return null when there's nothing left to read.

hrm I have the available() way working now but is it a poor design? I'm thinking that doing a while readObject != null is the better of the two?

That's how I've always done any file reading.
 

DWW

Platinum Member
Apr 4, 2003
2,030
0
0
Originally posted by: Templeton
Originally posted by: DWW
Originally posted by: Templeton
the readObject method should return null when there's nothing left to read.

hrm I have the available() way working now but is it a poor design? I'm thinking that doing a while readObject != null is the better of the two?

That's how I've always done any file reading.

Hrm looks like that method is throwing EOFException ;(

It will work but I don't want to catch any exceptions...should be a way to do it without I'd think.
 

DWW

Platinum Member
Apr 4, 2003
2,030
0
0
btw I'm doing this:

Object temp = null;

while ((temp = in.readObject()) != null)
.... stuff ...