Android学习笔记(11)————Android的私人文件夹的文件读写操作
/********************************************************************************************
* author:[email protected]大钟
* E-mail:[email protected]
* http://blog.****.net/conowen
* 注:本文为原创,仅作为学习交流使用,转载请标明作者及出处。
********************************************************************************************/
Android数据存储
Android的文件数据存储方式有几种方式,如Shared Preferences、Network、SQlite、File……
而File存储又可以以存放的位置分为,存放于应用程序的私有文件夹和SDcard目录里面。
今天就简单说说Android应用程序对私有文件夹的读写操作。
私有文件的存储
一个应用程序的私有文件夹位于/data/data/"应用程序的包名"/files文件夹下面。打开eclipse的DDMS可以通过查看File Explorer找到文件。
创建之后用户具有读写的权限,默认情况下,该文件是不能被其他应用程序访问的,但是可以更改权限。应用程序安装之后,可在Android“设置”选项里面清除该应用程序的数据。通过openFileOutput(String filename,mode)和openFileInput(String filename) 可以得到一个文件流(FileOutputStream)或者(FileIutputStream), 然后调用文件流的write方法或者read方法就可以实现“写”和“读”功能 。
写操作
openFileOutput(String filename,mode)———— 打开应用程序私有目录下的的指定私有文件(String filename)写入数据,
返回一个FileOutputStream 对象,如果文件不存在就创建这个文件。
官方说明
Parameters
name | The name of the file to open; can not contain path separators. |
---|---|
mode | Operating mode. Use 0 or MODE_PRIVATE for the default operation,MODE_APPEND to
append to an existing file,MODE_WORLD_READABLE andMODE_WORLD_WRITEABLE
to control permissions. |
Returns
- FileOutputStream Resulting output stream.
常量 含义MODE_PRIVATE
默认模式,值为0,文件只可以被调用该方法的应用程序访问
MODE_APPEND
如果文件已存在就向该文件的末尾继续写入数据,而不是覆盖原来的数据。(常用)
MODE_WORLD_READABLE
所有的应用程序都具有对该文件读的权限。
MODE_WORLD_WRITEABLE
所有的应用程序都具有对该文件写的权限。
写文件的简单过程
调用openFileOutput(String filename,mode)方法之后,会返回一个FileOutputStream对象。
然后调用FileOutputStream对象的write方法就可以写入文件了。
FileOutputStream.write(byte[] buffer) 虽然注意的是,write()方法写入的是byte[]类型,所以要通过
byte[] buffer = args.getBytes();转换,把为string类型的args转换为byte[]类型。然后再写入。其他操作方法:
读文件
openFileInput(String filename) 打开应用程序私有目录下的的指定私有文件以读入数据,返回一个FileInputStream 对象
列举文件
fileList() 搜索应用程序私有文件夹下的私有文件,返回所有文件名的String数组
删除文件
deleteFile(String fileName) 删除指定文件名的文件,成功返回true,失败返回false
具体用法还是看一下demo程序的代码,注释比较详细了
效果图
main.xml代码 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <EditText android:id="@+id/et" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/write" android:layout_width="80dip" android:layout_height="wrap_content" android:text="写" /> <Button android:id="@+id/read" android:layout_width="80dip" android:layout_height="wrap_content" android:text="读" /> <Button android:id="@+id/del" android:layout_width="80dip" android:layout_height="wrap_content" android:text="删" /> </LinearLayout>