Android用文件存儲數(shù)據(jù)的方法
本文實例為大家分享了Android用文件存儲數(shù)據(jù)的具體代碼,供大家參考,具體內(nèi)容如下
存儲數(shù)據(jù)示例:
private void saveFileData() {
BufferedWriter writer = null;
try {
FileOutputStream out = openFileOutput("data", MODE_PRIVATE);//保存的文件名為“data”
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write("this is a message");//文件中保存此字符串
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
從文件讀取數(shù)據(jù):
private void getFileData() {
BufferedReader reader = null;
try {
FileInputStream fileInputStream = openFileInput("data");
reader = new BufferedReader(new InputStreamReader(fileInputStream));
String line = "";
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("Test", "result data is " + result);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
注意:
1. openFileOutput()方法有兩個參數(shù):
第一個是文件名,可以不包含路徑,因為文件會默認存儲到data/data/包名/files目錄下。
第二個是操作模式,一般為MODE_PRIVATE,表示重復(fù)調(diào)用的話會覆蓋此文件的內(nèi)容。而MODE_APPEND表示在文件中追加內(nèi)容,不存在此文件就創(chuàng)建文件。
2.openFileInput()僅有一個參數(shù),即為要讀取數(shù)據(jù)的文件名。
3.文件存儲的方式不適合保存復(fù)雜的文本數(shù)據(jù),僅適合保存簡單的文本或者二進制數(shù)據(jù)。
4.必須添加try/catch捕獲異常,否則會報錯不能編譯。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Genymotion模擬器常見問題整理與相應(yīng)解決方法
為什么說是常見問題整合呢,因為小編我就是Genymotion模板器最悲劇的使用者,該見過的問題,我基本都見過了,在此總結(jié)出這血的教訓,望大家不要重蹈覆轍2018-03-03

