android file 存储 追加信息设置

/*转自本人新浪博中的记录,时间:2012-04-08 11:58:07

这两天在写android应用程序的时候用到了文件存储,只想以TXT格式存储,并将其存储到SD卡中,但是程序写好之后每次存储数据都刷新了,很郁闷,因为如果用FileOutputStream fos=openFileOutput(_sdpath1, MODE_APPEND);的话  我们就直接可以设置存储模式了,但是用FileOutputStream fos=new FileOutputStream(_sdpath1)这个就不知道怎么办了,研究了一下,原来FileOutPutStream也可以设置模式的,只是和openFileOutput不一样 我这样写FileOutputStream fos=new FileOutputStream(_sdpath1,Appendable);就可以实现数据追加功能,下面附上源码:

public void onClick(View v)
   {
    String string = "hello world!";
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
    {
     File path = Environment.getExternalStorageDirectory();
     String _sdpath1=path+"/dat.txt";
     Log.i("path:", _sdpath1);
     File myfile=new File(_sdpath1);
     try
     {
  
      //File myfile=new File("/sdcard/dat.txt");
      if(!myfile.exists())
      {
      myfile.createNewFile();
      FileOutputStream fos=new FileOutputStream(_sdpath1,Appendable);
      //FileOutputStream fos=new FileOutputStream(_sdpath1);
      //FileOutputStream fos=openFileOutput(_sdpath1, MODE_APPEND);
      //for(i=0;i<1000;i++)
      //{
      fos.write(string.getBytes());
      fos.write("\n".getBytes());
      //}
      fos.close();
         Toast.makeText(MainActivity.this, "save successful", 2000).show();
      }
      else {
       //FileOutputStream fos=new FileOutputStream(_sdpath1);
       FileOutputStream fos=new FileOutputStream(_sdpath1,Appendable);
       //FileOutputStream fos=openFileOutput(_sdpath1, MODE_APPEND);
       //for(i=0;i<1000;i++)
       //{
       fos.write(string.getBytes());
       fos.write("\n".getBytes());
       //}
       fos.close();
          Toast.makeText(MainActivity.this, "save successful2", 2000).show();
      }
     } catch (FileNotFoundException e)
     {
      Toast.makeText(MainActivity.this, "save fail", 2000).show();
      e.printStackTrace();
     } catch (IOException e)
     {
      Toast.makeText(MainActivity.this, "save fail2", 2000).show();
      e.printStackTrace();
     }
    }
   }
  });

 

当然 在manifest中也要注册啊:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值