This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Object Serialization" Watch "Object Serialization" New topic
Author

Object Serialization

Julien Castelain
Greenhorn

Joined: Sep 27, 2005
Posts: 28
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
Wanderer
Sheriff

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
    Greenhorn

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

    I changed the two methods for writing / reading

    no Exception this time
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Object Serialization
     
    Similar Threads
    MIDI Network Program Error
    ObjectOutputStream Make copy of Serialized File
    Serialization of ValueObject which contains static variables
    How to know the number of items in your Seralization/Deserialization stream?
    Problem with Object Desirialization