Android--持久化技术之文件存储

来源:互联网 发布:php博客系统实验 编辑:程序博客网 时间:2024/05/17 14:24

此乃本人的学习笔记   我只是将csdn博客做为一个记录学习的地方 So...微笑

</pre><span style="font-size:18px;">1.通过openFileOutput()方法创建一个FileOutputStream对象out</span><p></p><p><span style="font-size:18px;">2.通过out new一个OutputStreamWriter对象</span></p><p><span style="font-size:18px;">3.通过OutputStreamWriter对象 new 一个BufferedWriter对象writer</span></p><p><span style="font-size:18px;">4.通过writer.write(data)将字符串写入文件中  ps:data为字符串类型</span></p><p></p><p><pre name="code" class="java"><span style="font-size:18px;">public void save(){  String datta="我是字符串";  FileOutputStream out=null;  BufferedWriter writer=null;  try{    out=openFileOutput("data",Context.MODE_PRIVATE);    writer=new BufferedWriter(new OutputStreamWriter(out));    writer.write(data);  }catch(IOException e){     e.printStackTrace();  }finally{     try{       if(writer!=null){          writer.close();       }     }catch(IOException e){       e.printStackTrace();     }   }}</span>

openFileOutput()方法中有两个参数。第一个为你指定的文件名。该处文件名不包括路径(所有文件默认存储在/data/data/<packagename>/files/目录下)。第二个参数为文件的操作模式,有两个可选MODE_PRIVATE和MODE_APPEND。MODE_PRIVATE为默认参数,表示当指定同样的文件名时,所写入的内容将会覆盖原文件中的内容。MODE_APPEND表示如果该文件存在就往文件里追加内容,否则就创建新文件。

假如我们要存储EditText中的数据,我们首先在onCreate()中获得EditText的实例,在onDestory()方法中获取EditText中的输入内容,并调用save()方法把输入的内容存储到文件。

====================================================================================================================================

writer一定要记得close()掉,不然数据根本存不进文件 T_T

2016年5月9日

0 0