Jaffar Raza
Jaffar Raza

Reputation: 311

Writing data to the file in android

This code overwrites the file....

I want my previous data to remain the same..

osw..append (data);  

but did not get the result

public void WriteSettings(Context context, String data){ 
             FileOutputStream fOut = null; 
             OutputStreamWriter osw = null;

             try{
              fOut = context.openFileOutput("abc.txt",Context.MODE_PRIVATE);       
              osw = new OutputStreamWriter(fOut); 
              osw.write(data); 
              osw.flush(); 
              Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
              } 
              catch (Exception e) {       
              e.printStackTrace(); 
              Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
              } 
              finally { 
                 try { 
                        osw.close(); 
                        fOut.close(); 
                        } catch (IOException e) { 
                        e.printStackTrace(); 
                        } 
              } 
         }

Upvotes: 1

Views: 419

Answers (2)

Rakshi
Rakshi

Reputation: 6866

 public void WriteSettings(Context context, String data){ 
         FileOutputStream fOut = null; 
         OutputStreamWriter osw = null;

         try{
          fOut = context.openFileOutput("abc.txt",Context.MODE_APPEND);       
          osw = new OutputStreamWriter(fOut); 
          osw.write(data); 
          osw.flush(); 
          Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
          } 
          catch (Exception e) {       
          e.printStackTrace(); 
          Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
          } 
          finally { 
             try { 
                    osw.close(); 
                    fOut.close(); 
                    } catch (IOException e) { 
                    e.printStackTrace(); 
                    } 
          } 
     }

Upvotes: 2

hovanessyan
hovanessyan

Reputation: 31483

You have to use MODE_APPEND with openFileOutput.

Upvotes: 0

Related Questions