aspose file tools
The moose likes Beginning Java and the fly likes Object Serialization Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply 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: 18670
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://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
     
    subject: Object Serialization
     
    Similar Threads
    MIDI Network Program Error
    Problem with Object Desirialization
    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?