文件存儲(chǔ)
文件存儲(chǔ)時(shí)Android中最基本的一種數(shù)據(jù)存儲(chǔ)方式,它對(duì)存儲(chǔ)內(nèi)容不進(jìn)行任何的格式化處理,所有的數(shù)據(jù)都是原封不動(dòng)地保存到文件中,適合存儲(chǔ)一些文本數(shù)據(jù)或者二進(jìn)制數(shù)據(jù)。
將數(shù)據(jù)存儲(chǔ)到文件中
首先需要得到一個(gè)附著在文件上的輸出流,Context類(lèi)中提供了一個(gè)openFileOutput()方法,返回的輸出流用語(yǔ)將數(shù)據(jù)存儲(chǔ)到指定的文件中。該方法接收兩個(gè)參數(shù):
文件名:創(chuàng)建文件時(shí)使用這個(gè)名稱(chēng)。注意
指定的文件名不可以包含路徑,因?yàn)樗械奈募际悄J(rèn)存儲(chǔ)到/data/data/package name/files/目錄下-
文件的操作模式:主要有兩種,MODE_PRIVATE和MODE_APPEND。
- MODE_PRIVATE:是默認(rèn)操作模式,表示當(dāng)指定的文件存在時(shí),所寫(xiě)入的內(nèi)容將會(huì)覆蓋原文件中的內(nèi)容。
- MODE_APPEND:表示如果該文件已經(jīng)存在就繼續(xù)往里面寫(xiě)內(nèi)容,不存在久創(chuàng)建該文件。
另外還有兩種,MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE表示允許其他應(yīng)用對(duì)我們程序文件進(jìn)行讀寫(xiě)操作,已經(jīng)廢棄。
openFileOutput()方法返回一個(gè)FileOutputStream對(duì)象,得到該對(duì)象就可以使用java流的方式將數(shù)據(jù)寫(xiě)入文件中。
private void save(String input) {
FileOutputStream out = null;
BufferedWriter writer = null;
try {
try{
out = getActivity().openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(input);
}
finally {
if(writer != null)
writer.close();
if(out != null)
out.close();
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
從文件中讀取數(shù)據(jù)
類(lèi)似的我們需要先得到一個(gè)附著在文件上的輸入流,Context類(lèi)中提供了一個(gè)openFileInput()方法,返回的輸入流可以從文件中讀取數(shù)據(jù)。該方法只接收一個(gè)參數(shù):
- 文件名:根據(jù)指定文件名系統(tǒng)會(huì)自動(dòng)到/data/data/package name/files/目錄下去加載該文件,并返回一個(gè)FileInputStream對(duì)象。
得到了FileInputStream對(duì)象后,就可以使用java流的方式從文件中讀取數(shù)據(jù)。
private String load() {
FileInputStream in = null;
BufferedReader reader = null;
StringBuffer content = new StringBuffer();
try{
try{
in = getActivity().openFileInput("data");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine()) != null)
content.append(line + "\n");
}finally {
if(reader != null)
reader.close();
if(in != null)
in.close();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
實(shí)踐
