2 Replies Latest reply: Dec 23, 2006 9:44 PM by 807607 RSS

    FileOutputStream and ObjectOutputStream help

    807607
      I want to use FileOutputStream and ObjectOutputStream to save data for a program i am currently currently creating. The problem is i dont exactly know how to save it. Is there a method i can use to save it all or do i have to do them all seprate and what do i do to save certain types. I tried reading the explaination they have but i dont excatly understand it. I am better with reading code. So if you could show me where i would take and place code or what code i would do to save what. for example i need to save Images, Strings, and ints
                FileOutputStream fos = new FileOutputStream("SavedData.tmp");
                ObjectOutputStream oos = new ObjectOutputStream(fos);
      
                oos.writeObject(this);
           
                oos.close();
        • 1. Re: FileOutputStream and ObjectOutputStream help
          807607
          1) Scroll down a bit in the forum menu...There's a Serialization board there somewhere...
          2) For serialization, ALL of the data type's members must be a primitive type or implement Serializable. Strings can be serialized, but I don't know about Images...
          3)
          public void write(DataType dt) //Assuming that DataType follows rule #2
          {
          try
          {
          ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("MySerial.ser"));
          oos.writeObject(dt);
          oos.flush();
          oos.close();
          }
          catch(Exception e)
          {
          System.err.println("Error Writing :(...");
          }
          }
          
          public DataType read()
          {
          DataType ret = null;
          try
          {
          ObjectInputStream ois = new ObjectInputStream(new FileInputStream("MySerial.ser"));
          ret = (DataType)ois.readObject();
          ois.close();
          }
          catch(Exception e)
          {
          System.err.println("Error Reading :(...");
          }
          return(ret);
          }
          • 2. Re: FileOutputStream and ObjectOutputStream help
            807607
            class AnotherClass
            {
               .
               .
               .
               
               FileOutputStream fos = new FileOutputStream("SavedData.tmp");
               ObjectOutputStream oos = new ObjectOutputStream(fos);
            
               SomeClass[] array = new SomeClass[10];
               for (int x = 0 ; x < 10 ; x++)
                  array[x] = new SomeClass();
            
               oos.writeObject(array);
               oos.close();
            }
            
            class SomeClass
            {
               Image image;
               String string;
               int number;
               .
               .
               .
            }