0

Hi I have an issue when trying to append new objects to the existing file.. Once the android app has been lunched again I want to get the existing file and add a new objects then read the objects from the existing file ... Actually, when I'm trying to read the object, the code will read only the first objects .. You can find below the code .. Could you please help ? Thanks

using the following method to write an objects :

 public void saveObject(Person p, File f){
     try
     {

         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f, true));
         oos.writeObject(p);
         oos.reset();
         oos.flush(); 
         oos.close();


     }
     catch(Exception ex)
     {
        Log.v("Serialization Save Error : ",ex.getMessage());
        ex.printStackTrace();
     }
}

Using the following method to read an objects :

    public Object loadSerializedObject(File f)
{

       try {
          ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
           try{
              Object loadedObj = null;
              while ((loadedObj = ois.readObject()) != null) {
              Log.w(this.getClass().getName(), "ReadingObjects") ;

            }
              return objects;
           }finally{
               ois.close();
           }

       } catch (StreamCorruptedException e) {
           e.printStackTrace();
       } catch (IOException e) {

           e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
       return null;
}
Darwind
  • 7,284
  • 3
  • 49
  • 48
AndroidCoder
  • 3
  • 1
  • 2
  • When you *return objects*: where is **objects** declared? where do you assing any value to **objects**? – ilomambo Feb 13 '13 at 11:42
  • Could it be that you're writing different objects to different files and if so are you actually fetching all objects you've written to files? – Darwind Feb 13 '13 at 11:51

1 Answers1

0

Unfortunately you can't create a new ObjectOutputStream every time you want to append to the stream and then read everything back with a single stream. The constructor adds headers to the underlying stream before you start writing objects. You are probably seeing the java.io.StreamCorruptedException: invalid type code: AC exception, that's because the first header is 0xAC.

I don't know how many objects you are dealing with, but one option might be to read all your objects and then rewriting them all using a single ObjectOutputStream. That can get pricy if there are lots of objects. Alternatively, you might want to consider managing the serialization yourself manually through Externalizable. It can get painful though.

mprivat
  • 21,582
  • 4
  • 54
  • 64