檔案存儲資料使用了java中的io操作來進行檔案的儲存和讀取。針對檔案的操作主要是以下三種:
1.建立或打開檔案
2.讀取檔案
3.删除檔案
1.通過context.openfileoutput擷取輸出流
<code></code>
/*
* name 打開或建立檔案的名稱
* mode 打開或建立檔案的模式
*/
fileoutputstream openfileoutput (string name, int mode)
tip:建立的存儲檔案儲存在/data/data/<package name>/files檔案夾下
2.四種檔案儲存的模式
context.mode_private = 0
context.mode_world_readable = 1
context.mode_world_writeable = 2
context.mode_append = 32768
mode_private 為預設操作模式,代表該檔案是私有資料,隻能被應用本身通路,在該模式下寫入的内容會覆寫原檔案的内容。
mode_world_readable 表示目前檔案可以被其他應用讀取。
mode_world_writeable 表示目前檔案可以被其他應用寫入。
mode_append 檢查檔案是否存在,存在就往檔案追加内容,否則就建立新檔案。
tip:在使用模式時,可以用"+"來選擇多種模式,比如openfileoutput(filename, context.mode_private + mode_world_readable)
android有一套自己的安全模型,當應用程式(.apk)在安裝時系統就會配置設定給他一個userid,當該應用要去通路其他資源比如檔案的時候,就需要userid比對。預設情況下,任何應用建立的檔案,sharedpreferences,資料庫都應該是私有的
通過context.openfileinput擷取輸入流。
/*
fileinputstream openfileinput (string name)
* name 删除檔案的名稱
* return 成功傳回true,反之false
boolean deletefile (string name)
getfilesdir()可以擷取到"/data/data/<package name>/files"
getcachedir()可以擷取到"/data/data/<package name>/cache"
1.操作sdcard需要的權限
<!-- 在sdcard中建立與删除檔案權限 -->
<uses-permission android:name="android.permission.mount_unmount_filesystems"/>
<!-- 往sdcard寫入資料權限 -->
<uses-permission android:name="android.permission.write_external_storage"/>
2.要往sdcard存放檔案,程式必須先判斷手機是否裝有sdcard,并且可以進行讀寫。可以通過getexternalstoragestate ()獲得sdcard狀态
傳回的狀态如下:
environment.media_bad_removal:bad_removal ——media remote before unmount
environment.media_checking:checking——media present(已插入) and being disk-check
environment.media_mounted:mounted——media present and mounted and can be read/write
environment.media_mounted_read_only:mounted_ro——media present and mounted and can be read
environment.media_nofs:nofs——media present but filesytem not support
environment.media_removed:removed——media not present
environment.media_shared:shared——media present and not mount. and share
environment.media_unmountable:unmountable——media present but can not mount
environment.media_unmounted:unmounted——media present but not mount
3.擷取sdcard目錄
* return sdcard的目錄file
file getexternalstoragedirectory ()