开发者

Android:Writing data to a file

with the below piece of code, I'm able to create a new fil开发者_如何学编程e 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();
                        }


Try setting the append flag to true when constructing your FileOutputStream

osr = new FileOutputStream(outputFile, true);


Try,

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜