m7m
m7m

Reputation: 13

Append object to a existing file in android

i have append an object to a existing file but i can not read it ,i can read the first object and this is my code What is the problem ??

try{

       FileOutputStream fos = openFileOutput("f.txt",MODE_PRIVATE | MODE_APPEND );

       ObjectOutputStream oos = new ObjectOutputStream(fos);
       String a=new String ("Hello  object1 ");
       String b=new String("Hello  object2 ");
       String c=new String("Hello  object3 ");

       oos.writeObject(a);
       oos.writeObject(b);
       oos.writeObject(c);
       oos.close();

       // Reading it back..

       FileInputStream fis = openFileInput("f.txt");

       ObjectInputStream ois = new ObjectInputStream(fis);

       //ois=new ObjectInputStream(fis);
       //  r=(String)ois.readObject(); 
              String r;
       while ((r= (String)ois.readObject()) != null) {
          Log.i("while Read r",r);

          Toast.makeText(getApplicationContext(),r, Toast.LENGTH_SHORT).show();
       }

       ois.close();

       }catch (Exception e){
           Log.i("Exception",e.getMessage());
       }

I hope you can help me!! thanks.

Upvotes: 1

Views: 1179

Answers (1)

Soheil
Soheil

Reputation: 753

The code seems correct just some modification in "While" , Check below:

try{

   FileOutputStream fos = openFileOutput("f.txt",MODE_PRIVATE | MODE_APPEND );

   ObjectOutputStream oos = new ObjectOutputStream(fos);
   String a=new String ("Hello  object1 ");
   String b=new String("Hello  object2 ");
   String c=new String("Hello  object3 ");

   oos.writeObject(a);
   oos.writeObject(b);
   oos.writeObject(c);
   oos.close();

   // Reading it back..

   FileInputStream fis = openFileInput("f.txt");

   ObjectInputStream ois = new ObjectInputStream(fis);

   //ois=new ObjectInputStream(fis);
   //  r=(String)ois.readObject(); 
          String r;
   while (fis.available() > 0) {
      r= (String)ois.readObject();
      Log.i("while Read r",r);

      Toast.makeText(getApplicationContext(),r, Toast.LENGTH_SHORT).show();
   }

   ois.close();

   }catch (Exception e){
       Log.i("Exception",e.getMessage());
   }

Upvotes: 1

Related Questions