Android学习 —— 数据的存储与访问方式一: 文件存取
筆記摘要:
在Android中主要提供了四種數據存儲與訪問的方式,文件、SharedPreference(偏好參數保存)、SOLite數據庫、內容提供者(Content?provider)和網絡,
? ? 本篇文章先介紹使用文件的方式進行數據的存儲和訪問,其中重點介紹了它的四種操作模式。
使用文件進行存儲
方式一:通過openFileOutput()直接把數據輸出到文件中
Activity提供了openFileOutput()方法可以用于把數據輸出到文件中,具體的實現過程與在J2SE環境中保存數據到文件中是一樣的
public class FileActivity extends Activity {@Override public void onCreate(Bundle savedInstanceState) {... FileOutputStream outStream = this.openFileOutput("test.txt", Context.MODE_PRIVATE);outStream.write("這是一個使用文件進行存儲的示例".getBytes());outStream.close();   }
}openFileOutput()方法的第一參數用于指定文件名稱,不能包含路徑分隔符“/”?,如果文件不存在,Android?會自動創建它。
創建的文件保存在/data/data/<package?name>/files目錄:openFileOutput()。方法的第二參數用于指定操作模式.
方式二:通過getFilesDir()先獲取文件的路徑:/data/data/<package?name>/files目錄
public static boolean saveInfoToFile(Context context){try {File parentfile = context.getFilesDir();//  /data/data/com.itxushuai.login/filesFile des = new File(parentfile,"info.txt");//  /data/data/com.itxushuai.login/files/info.txtFileOutputStream fos = new FileOutputStream(des);fos.write("文件存入".getBytes());fos.close();return true ;} catch (Exception e) {e.printStackTrace();return false;}文件操作的有四種模式:?
Context.MODE_PRIVATE????=??0
Context.MODE_APPEND????=??32768
Context.MODE_WORLD_READABLE?=??1
Context.MODE_WORLD_WRITEABLE?=??2
Context.MODE_PRIVATE:
? ? ? ? 為默認操作模式,由PRIVATE就可知道該文件是私有的,只能被應用本身訪問,在該模式下,寫入的內容會覆蓋原文件的內容,
? ? ? ??如果想把新寫入的內容追加到原文件中。可以使用Context.MODE_APPEND
Context.MODE_APPEND:
? ? ? ? 模式會檢查文件是否存在,存在就往文件追加內容,否則就創建新文件。
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用來控制其他應用是否有權限讀寫該文件。
MODE_WORLD_READABLE:
? ? ? ??表示當前文件可以被其他應用讀取。
MODE_WORLD_WRITEABLE:
? ? ? ??表示當前文件可以被其他應用寫入。
如果希望文件被其他應用讀和寫,可以將READABLE?與WRITEABLE組合起來使用:?
? ? ? ??openFileOutput("file.txt",Context.MODE_WORLD_READABLE?+?Context.MODE_WORLD_WRITEABLE);
Tip
android有一套自己的安全模型,當應用程序(.apk)在安裝時系統就會分配給他一個userid,當該應用要去訪問其他資源比如文件的時候,就需要userid匹配。默認情況下,任何應用創建的文件,sharedpreferences,數據庫都應該是私有的(位于/data/data/<package?name>/files),其他程序無法訪問。除非在創建時指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE?,只有這樣其他程序才能正確訪問。
示例演示:
說明:
? ? ? ? ? ? 1)模擬用戶登陸界面,向文件中寫入用戶的用戶名和密碼,并在用戶下一次登陸的時候,實現回顯功能。
? ? ? ? ? ? 2)向SD卡中寫入文件,記得在AndroidMainfest.xml文件中配置讀寫權限。
? ? ? ? ? ? 3)四種模式文件的寫入
配置權限
 <!--在manifest節點下添加SD卡寫入和讀取權限  -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity" ><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/username"/><EditText android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="text"android:id="@+id/username_et"/><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/password" /><EditText android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="textPassword"android:id="@+id/password_et"/><RadioGroup android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/radioGroup_id"><RadioButton android:text="default"android:id="@+id/default_radioButton"android:layout_width="wrap_content"android:layout_height="wrap_content"/><RadioButton android:text="private"android:id="@+id/private_radioButton"android:layout_width="wrap_content"android:layout_height="wrap_content"/><RadioButton android:text="readable"android:id="@+id/readable_radioButton"android:layout_width="wrap_content"android:layout_height="wrap_content"/><RadioButton android:text="writable"android:id="@+id/writable_radioButton"android:layout_width="wrap_content"android:layout_height="wrap_content"/></RadioGroup><RelativeLayout android:layout_width="match_parent"android:layout_height="wrap_content"><CheckBoxandroid:id="@+id/rem_checkBox"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:text="保存登陸信息" /><Button android:id="@+id/saveBtn"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:text="保存"/>
</RelativeLayout></LinearLayout>MainActivity
import java.util.HashMap;import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;import com.itxushuai.login.service.LoginService;public class MainActivity extends Activity implements OnClickListener{private static final String TAG = "MainActivity";private EditText username_et;private Button saveBtn;private EditText password_et ;private CheckBox rem_checkBox ;private RadioGroup radioGroup_id ;private boolean show = false;//當Activity被創建的時候調用@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//根據ID獲取各個組件saveBtn = (Button) findViewById(R.id.saveBtn);username_et = (EditText) findViewById(R.id.username_et);password_et = (EditText) findViewById(R.id.password_et);rem_checkBox = (CheckBox) findViewById(R.id.rem_checkBox);radioGroup_id = (RadioGroup) findViewById(R.id.radioGroup_id);//調用回顯用戶信息的方法showData();//為保存按鈕設置事件監聽saveBtn.setOnClickListener(this);}//回顯用戶信息的方法public void showData(){//模擬從數據庫中查找用戶數據,并回顯,由于原來數據庫(這里是文件)中沒有用戶的信息,所以這第一次使用的時候會出現NullPointerException,//所以這里設置一個標志,當存入數據的時候,設置為trueif(show){HashMap<String,String> map = (HashMap<String, String>) LoginService.readInfoFromFile2(this);String username = map.get("username");String password = map.get("password");username_et.setText(username);password_et.setText(password);rem_checkBox.setChecked(true);}}//當用戶點擊按鈕的時候執行@Overridepublic void onClick(View v) {//獲取文本框中的內容String username = username_et.getText().toString().trim();String password = password_et.getText().toString().trim();Log.i(TAG,"onclick..........");boolean result = false;//設置一個boolean類型的值,表示保存是否成功//對用戶名和密碼進行簡單的合理性判斷if(TextUtils.isEmpty(username)||TextUtils.isEmpty(password)){Toast.makeText(this, "用戶名或密碼不能為空", Toast.LENGTH_LONG).show();//用戶名和密碼不能為nullreturn;}else{//如果用戶勾選了保存登陸信息按鈕就將登陸信息存入文件中if(rem_checkBox.isChecked()){Log.i(TAG,"保存用戶名和密碼");int rg_id = radioGroup_id.getCheckedRadioButtonId();//對文件進行保存if(v.getId() == R.id.saveBtn){result = LoginService.saveInfoToFile(this,username,password);//result = LoginService.saveInfoToSD(this,username,password);//將文件存入SD卡show = true;	//已經保存了數據,將回顯標志設為true,以便在第二次登陸的時候顯示用戶信息}//寫入不同模式的文件,為演示做準備switch(rg_id){case R.id.default_radioButton:result =  LoginService.saveInfoToFile(this,username, password);break;case R.id.private_radioButton:result = LoginService.saveInfoToPrivateFile(this, username, password);break;case R.id.readable_radioButton:result = LoginService.saveInfoToReadableFile(this, username, password);break;case R.id.writable_radioButton:result = LoginService.saveInfoToWritableFile(this, username, password);break;}//保存成功,Toast一下if(result){Toast.makeText(this, "保存成功", Toast.LENGTH_LONG).show();}else{Toast.makeText(this, "保存失敗", Toast.LENGTH_LONG).show();}//這里是對數據庫中的用戶名和密碼獲取并進行驗證,此處略去//   ..............}}}
}業務類:提供四種文件模式以及SD卡的寫入
package com.itxushuai.login.service;import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;import android.content.Context;
import android.graphics.AvoidXfermode.Mode;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;public class LoginService {private static final String TAG = null;/*** 保存用戶名密碼到手機里面的文件(默認模式:PRIVATE)* * @param context  上下文 提供一些信息 提供一些環境 幫助類* @param username 用戶名* @param password 密碼* @return 是否保存成功*/public static boolean saveInfoToFile(Context context, String username, String password){try {File parentfile = context.getFilesDir();//  /data/data/com.itxushuai.login/filesFile des = new File(parentfile,"info.txt");//  /data/data/com.itxushuai.login/files/info.txtFileOutputStream fos = new FileOutputStream(des);String info = username+"&"+password;fos.write(info.getBytes());fos.close();return true ;} catch (Exception e) {e.printStackTrace();return false;}}/*** 將用戶名密碼保存到私有模式的文件中*/public static boolean saveInfoToPrivateFile(Context context, String username, String password){try{FileOutputStream fos = context.openFileOutput("private.txt",Context.MODE_PRIVATE);String info = username+"&"+password;fos.write(info.getBytes());fos.close();return true ;} catch (Exception e) {e.printStackTrace();return false;}}/*** 將用戶名密碼到可讀模式的文件中*/public static boolean saveInfoToReadableFile(Context context, String username, String password){try {Log.i(TAG,"saveInfoToReadableFile");FileOutputStream fos = context.openFileOutput("readable.txt",Context.MODE_WORLD_READABLE);String info = username+"&"+password;fos.write(info.getBytes());fos.close();return true ;} catch (Exception e) {e.printStackTrace();return false;}}/*** 將用戶名密碼到可寫模式的文件中*/public static boolean saveInfoToWritableFile(Context context, String username, String password){try {FileOutputStream fos = context.openFileOutput("writable.txt",Context.MODE_WORLD_WRITEABLE);String info = username+"&"+password;fos.write(info.getBytes());fos.close();return true ;} catch (Exception e) {e.printStackTrace();return false;}}/*** 將用戶名密碼到可讀可寫模式的文件中*/public static boolean saveInfoToPublicFile(Context context, String username, String password){try {FileOutputStream fos = context.openFileOutput("public.txt",Context.MODE_WORLD_WRITEABLE+Context.MODE_WORLD_WRITEABLE);String info = username+"&"+password;fos.write(info.getBytes());fos.close();return true ;} catch (Exception e) {e.printStackTrace();return false;}}/*** 將用戶名密碼到SD卡中*/public static boolean saveInfoToSD(Context context,String username,String password){try {//判斷SD卡是否存在if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){//獲取SD卡的路徑并創建一個目的文件File sdFile = new File(Environment.getExternalStorageDirectory(),"sdFile");FileOutputStream fos = new FileOutputStream(sdFile);fos.write((username+"&"+password).getBytes());fos.close();return true;}else {Toast.makeText(context, "sd卡不存在", Toast.LENGTH_SHORT).show();return false;}}catch (Exception e) {e.printStackTrace();return false;}}/*** 獲取保存在文件里面的用戶名 和密碼:context.getFilesDir()* @param context* @return*/public static Map readInfoFromFile(Context context){try {File parentfile = context.getFilesDir();File srcFile = new File(parentfile,"private.txt");FileInputStream fis = new FileInputStream(srcFile);BufferedReader bis = new BufferedReader(new InputStreamReader(fis));String result = bis.readLine();String username = result.split("&")[0];String password = result.split("&")[1];Map<String,String> map = new HashMap<String,String>();map.put("username", username);map.put("password", password);bis.close();return map;} catch (Exception e) {e.printStackTrace();return null;}}/*** 獲取保存在文件里面的用戶名 和密碼: context.openFileInput("info.txt");*/public static Map  readInfoFromFile2(Context context){try {FileInputStream fileInStream = context.openFileInput("info.txt");BufferedReader bis = new BufferedReader(new InputStreamReader(fileInStream));String result = bis.readLine();String username = result.split("&")[0];String password = result.split("&")[1];Map<String,String> map = new HashMap<String,String>();map.put("username", username);map.put("password", password);bis.close();return map;} catch (Exception e) {e.printStackTrace();return null;}} 
} OtherActivity:演示在一個應用中讀取另外一個應用中的文件
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity" ><Buttonandroid:id="@+id/default_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="讀默認文件" /><Buttonandroid:id="@+id/private_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="讀私有文件" /><Buttonandroid:id="@+id/readable_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="讀可讀文件" /><Buttonandroid:id="@+id/writatble_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="讀可寫文件" /><Buttonandroid:id="@+id/read_and_writatble_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="讀可讀可寫文件" />
</LinearLayout>MainActivity
package com.itxushuai.other;import com.itxushuai.service.ReadFile;import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;public class MainActivity extends Activity implements OnClickListener{private static final String TAG = "MainActivity";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button defaultBtn = (Button) findViewById(R.id.default_id);Button privateBtn = (Button) findViewById(R.id.private_id);Button readableBtn = (Button) findViewById(R.id.readable_id);Button writeBtn = (Button) findViewById(R.id.writatble_id);Button read_and_writatbleBtn= (Button) findViewById(R.id.read_and_writatble_id);defaultBtn.setOnClickListener(this);privateBtn.setOnClickListener(this);readableBtn.setOnClickListener(this);writeBtn.setOnClickListener(this);read_and_writatbleBtn.setOnClickListener(this);}@Overridepublic void onClick(View v) {switch(v.getId()){case R.id.default_id:ReadFile.readDefaultFile(this);break;case R.id.private_id:ReadFile.readPrivateFile(this);break;case R.id.readable_id:ReadFile.readReadableFile(this);break;case R.id.writatble_id:ReadFile.readWritableFile(this);break;case R.id.read_and_writatble_id:ReadFile.readPublicFile(this);break;}}
}
  import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;import android.content.Context;
import android.util.Log;
import android.widget.Toast;public class ReadFile {private static final String TAG = "ReadFile";//讀取缺省模式的文件public static void readDefaultFile(Context context){File file = new File("/data/data/com.itxushuai.login/files/info.txt");Log.i(TAG, "readDefaultFile............");FileInputStream fis;try {fis = new FileInputStream(file);BufferedReader bufr = new BufferedReader(new InputStreamReader(fis));String msg = bufr.readLine();bufr.close();Toast.makeText(context, msg, 0).show();} catch (Exception e) {e.printStackTrace();}}//讀取私有模式的文件public static void readPrivateFile(Context context){File file = new File("/data/data/com.itxushuai.login/files/private.txt");Log.i(TAG, "readPrivateFile............");FileInputStream fis;try {fis = new FileInputStream(file);BufferedReader bufr = new BufferedReader(new InputStreamReader(fis));String msg = bufr.readLine();bufr.close();Toast.makeText(context, msg, 0).show();} catch (Exception e) {e.printStackTrace();}}//讀取可讀模式的文件public static void readReadableFile(Context context){Log.i(TAG, "readReadableFile............");File file = new File("/data/data/com.itxushuai.login/files/readable.txt");FileInputStream fis;try {fis = new FileInputStream(file);BufferedReader bufr = new BufferedReader(new InputStreamReader(fis));String msg = bufr.readLine();bufr.close();Toast.makeText(context, msg, 0).show();} catch (Exception e) {e.printStackTrace();}}//讀取可寫模式的文件public static void readWritableFile(Context context){Log.i(TAG, "readWritableFile............");File file = new File("/data/data/com.itxushuai.login/files/writable.txt");FileInputStream fis;try {fis = new FileInputStream(file);BufferedReader bufr = new BufferedReader(new InputStreamReader(fis));String msg = bufr.readLine();bufr.close();Toast.makeText(context, msg, 0).show();} catch (Exception e) {e.printStackTrace();}}
}讀取各種模式文件時Logcat捕捉的信息:
轉載于:https://www.cnblogs.com/xushuai123/archive/2013/04/17/3634413.html
總結
以上是生活随笔為你收集整理的Android学习 —— 数据的存储与访问方式一: 文件存取的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 《凉夜有怀》第七句是什么
 - 下一篇: 亚龙湾看日落最美的地方