/*转自本人新浪博中的记录,时间: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"/>