您的位置:首页 > 移动开发 > Android开发

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

2016-05-09 23:04 387 查看
此乃本人的学习笔记   我只是将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日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  存储