本文實(shí)例為大家分享了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ù):
第一個是文件名,可以不包含路徑,因?yàn)槲募J(rèn)存儲到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ù),僅適合保存簡單的文本或者二進(jìn)制數(shù)據(jù)。
4.必須添加try/catch捕獲異常,否則會報(bào)錯不能編譯。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選