save and load object to file how do i do


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: save and load object to file how do i do

  1. #1
    Join Date
    Nov 2004
    Posts
    1

    save and load object to file how do i do

    hello
    i am a programmer (but do not have so much experience in java more c, c++ and matlab)
    i have a question
    how do i copy an object to a file?
    i have Object obj and i want to have a class with two methods save ( save it to a file') and load (open this saved file)
    class SaveFile {
    Object obj
    // other fields perhaps if it is necessary

    public save (Object obj) {
    // save an object to a file. object is given as parameter

    //code if which i don't know how to write and i need help from you
    }
    public load (object obj) {
    // open the object from file. Object (or maybe the file name is given as parameter)
    //code if which i don't know how to write and i need help from you
    }
    i believe it is a standard think whith a standard solution so i hope people can show the complete code (or pseudocode) because i am not so good in java's io.package

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Check out the java.io.Serializable interface and the java.io.ObjectOutput/InputStream This requires to methods per class, one for reading and one for writing the class.
    You my then do like:

    MyClass onObj;
    .
    .
    FileOutputStream outStream new FileOutputStream("c:\whatevver.datar");
    ObjectOutputStream out = new ObjectOutputStream(outStream);
    out.writeObject(anObj);
    out.flush();
    out.close();
    .
    Note, the read and write methods may themselves call the class' inner objects serialization metods. So, if you have a vector of your class, then using the writeObject for the Vector will in turn call your class objects serialization methods.
    eschew obfuscation

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center