m4n07
m4n07

Reputation: 2297

Android:Writing data to a file

with the below piece of code, I'm able to create a new file called output.txt and i'm able to write data. Problem is this file gets recreated once i close my app and then open my app again. As because i create this in onCreate().

But i would like to have the file created only once and then i would like to append the data there after.

private File outputFile = null;
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;


        @Override
     public void onCreate(Bundle savedInstanceState) {
       ....
      if(outputFile == null)
               outputFile = new  File("/storage/new/output.txt");

             if(osr==null){
               try {
                   osr = new FileOutputStream(outputFile);
                   out = new DataOutputStream(osr);
               } catch (FileNotFoundException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
               }
             }

             .....
                 try {
                            out.writeBytes(data);
                                out.flush();
                            //out.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

Upvotes: 1

Views: 7406

Answers (2)

David Snabel-Caunt
David Snabel-Caunt

Reputation: 58371

Try setting the append flag to true when constructing your FileOutputStream

osr = new FileOutputStream(outputFile, true);

Upvotes: 5

Ben Williams
Ben Williams

Reputation: 6167

Try,

FileOutputStream fileOut = openFileOutput(outputFile, MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fileOut);
osw.writeBytes(data);
osw.flush();

Upvotes: 1

Related Questions