permaculture playing cards
The moose likes Beginning Java and the fly likes Object Serialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Object Serialization" Watch "Object Serialization" New topic

Object Serialization

Julien Castelain

Joined: Sep 27, 2005
Posts: 29
hi all,

i'm trying acheive a simple task :

1 - Create one (or many) custom object(s)
2 - Save them to a file
3 - Read the objects from the file

1 - i created a class called "Client" that implements Serializable

2 - here's the way i thought of saving these object :
use an ArrayList (clients) to store the objects
every time a new "Client" object is created, add it
to the ArrayList...
when it comes to "saving" the objects

3 - this seems to work so i'll try to read the objects

i get an Exception (i guess i have reached the end of the file)
, but how do i know when i have to stop "reading" ?

thanks for your help
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Unfortunately serialization does not offer an elegant way to detect the last object without throwing an error, once they have been serialized this way. You have several alternatives:
  • Serialize the entire ArrayList at once. This will serialize the contents as well. (You could also serialize an array instead.)
  • Use writeInt() to write the number of objects in the list, [i]before[i] you write all the individual objects. Then before deserializing use readInt() to read the number of objects, then loop to read only that number of objects.
  • Create a special object which signals the end of input.

  • "I'm not back." - Bill Harding, Twister
    Julien Castelain

    Joined: Sep 27, 2005
    Posts: 29
    Thanks Jim,

    I changed the two methods for writing / reading

    no Exception this time
    I agree. Here's the link:
    subject: Object Serialization
    It's not a secret anymore!