Android 数据存储之文件存储小记
前言
Android操作文件的方式和JAVA I/O操作是十分類似的,在這個(gè)我小談一下。
Android寫入文件
在Android中Context類提供了openFileOutput()方法,用于文件寫入。默認(rèn)存儲(chǔ)路徑為/data/data/<package name>/files/中。
openFileOutput原型:
public FileOutputStream openFileOutput(String name, int mode)throws FileNotFoundException {return mBase.openFileOutput(name, mode); }第二個(gè)參數(shù)mode有4個(gè)類型:
MODE_APPEND:檢查文件是否存在,存在就往文件追加內(nèi)容,否則就創(chuàng)建新文件。
MODE_PRIVATE:為默認(rèn)操作模式,代表該文件是私有數(shù)據(jù),只能被應(yīng)用本身訪問,在該模式下,寫入的內(nèi)容會(huì)覆蓋原文件的內(nèi)容,如果想把新寫入的內(nèi)容追加到原文件中。
MODE_WORLD_READABLE:表示當(dāng)前文件可以被其他應(yīng)用讀取
MODE_WORLD_WRITEABLE:表示當(dāng)前文件可以被其他應(yīng)用寫入
寫入例子福利:
public void write(String inputText){FileOutputStream out = null;BufferedWriter writer = null;try {out = openFileOutput("data", Context.MODE_PRIVATE);writer = new BufferedWriter(new OutputStreamWriter(out));writer.write(inputText);} catch (Exception e) {e.printStackTrace();} finally {try {if (writer != null) {writer.close();}} catch (Exception e2) {e2.printStackTrace();}} }Android讀取文件
同樣,在Android中Context類還提供了openFileInput()方法,用于文件寫入。
openFileInput原型:
public FileInputStream openFileInput(String name)throws FileNotFoundException {return mBase.openFileInput(name); }參數(shù)很簡單,就一個(gè)文件名。
讀取例子福利:
public String load(String fileName){FileInputStream in = null;BufferedReader reader = null;StringBuilder content = new StringBuilder();try {in = openFileInput(fileName);reader = new BufferedReader(new InputStreamReader(in));String line = "";while((line = reader.readLine()) != null){content.append(line);}} catch (Exception e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (Exception e2) {e2.printStackTrace();}}}return content.toString();} }總結(jié)
文件讀取的核心就是Context提供的openFileInput()和openFileOutput(),操作起來很簡單,但是不適合用于保存一些復(fù)雜的文本數(shù)據(jù)。
博客名稱:王樂平博客
博客地址:http://blog.lepingde.com
CSDN博客地址:http://blog.csdn.net/lecepin
總結(jié)
以上是生活随笔為你收集整理的Android 数据存储之文件存储小记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2022五一杯数学建模
- 下一篇: Android loading进度条使用