在 Android 應用開發中,數據的持久化儲存是每一個程式設計師都必須掌握的核心技能。本文將由淺入深地介紹四種常見的本地數據處理方式,分別是 SharedPreferences、自訂檔案、res/raw 唯讀資源以及 SD 卡,並附上完整的程式碼示範,幫助你靈活應對不同場景下的數據儲存需求。
一、使用 SharedPreferences 處理數據
SharedPreferences 會將資料以 XML 檔案的形式保存,內容以節點的方式組織在檔案中。它為開發者提供了一系列便捷的 API,可以輕鬆完成資料的新建、儲存、讀取與刪除。
首先在介面中輸入需要保存的內容,這裡我們以姓名與號碼為例:

輸入姓名:雨松MOMO
輸入號碼:15810463139

點擊儲存按鈕後,系統會提示保存成功。

保存成功後,資料會被寫入到 data 路徑下的「當前包名/shared_prefs/main.xml」檔案中。用編輯器打開這個檔案,可以清楚看到內容是以一個個節點的形式存儲在 XML 裡的。

SharedPreferences 提供了非常方便的方法來讀寫資料。需要特別說明的是,一個應用中可以同時存在多個 SharedPreferences 檔案,程式只需根據不同的 XML 名稱,就能透過對應的方法取得 respective 物件。由於它並不支援高效的批次遍歷查詢,因此在開發實務中,我們通常用它來存放一些零散、量小的資料,例如使用者設定的音量大小、上次輸入的搜尋關鍵字等等。
Java 程式碼:
- public class SPActivity extends Activity {
-
- /**使用SharedPreferences 來儲存與讀取數據**/
- SharedPreferences mShared = null;
-
- /**程序中可以同時存在多個SharedPreferences數據, 根據SharedPreferences的名稱就可以拿到對象**/
- public final static String SHARED_MAIN = "main";
-
- /**SharedPreferences中儲存數據的Key名稱**/
- public final static String KEY_NAME = "name";
- public final static String KEY_NUMBER = "number";
-
- /**SharedPreferences中儲存數據的路徑**/
- public final static String DATA_URL = "/data/data/";
- public final static String SHARED_MAIN_XML = "main.xml";
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- setContentView(R.layout.sharedpreferences);
- /**拿到名稱是SHARED_MAIN 的SharedPreferences對象**/
- mShared = getSharedPreferences(SHARED_MAIN, Context.MODE_PRIVATE);
- /**拿到SharedPreferences中保存的數值 第二個參數為如果SharedPreferences中沒有保存就賦一個默認值**/
- String name = mShared.getString(KEY_NAME, "數據庫中沒有儲存姓名");
- String number = mShared.getString(KEY_NUMBER, "數據庫中沒有儲存號碼");
-
- final EditText editName = (EditText)findViewById(R.id.sp_et0);
- final EditText editNumber = (EditText)findViewById(R.id.sp_et1);
- editName.setHint("上次輸入的姓名為【 " +name+"】");
- editNumber.setHint("上次輸入的號碼為【 " +number+"】");
-
- Button button0 = (Button)findViewById(R.id.sp_button0);
-
- /**監聽按鈕點擊後保存用戶輸入信息到SharedPreferences中**/
- button0.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View arg0) {
- /**拿到用戶輸入的信息**/
- String name = editName.getText().toString();
- String number = editNumber.getText().toString();
- /**開始保存入SharedPreferences**/
- Editor editor = mShared.edit();
- editor.putString(KEY_NAME, name);
- editor.putString(KEY_NUMBER, number);
- /**put完畢必需要commit()否則無法保存**/
- editor.commit();
- ShowDialog("保存SharedPreferences成功");
-
- }
- });
-
- Button button1 = (Button)findViewById(R.id.sp_button1);
- button1.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View arg0) {
- /**開始清除SharedPreferences中保存的內容**/
- Editor editor = mShared.edit();
- editor.remove(KEY_NAME);
- editor.remove(KEY_NUMBER);
- //editor.clear();
- editor.commit();
- ShowDialog("清除SharedPreferences數據成功");
- }
- });
-
- Button button2 = (Button)findViewById(R.id.sp_button2);
- button2.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View arg0) {
- /** 刪除SharedPreferences文件 **/
- File file = new File(DATA_URL + getPackageName().toString()
- + "/shared_prefs", SHARED_MAIN_XML);
- if (file.exists()) {
- file.delete();
- }
- ShowDialog("刪除SharedPreferences文件成功");
- }
- });
-
- super.onCreate(savedInstanceState);
- }
-
- public void ShowDialog(String string) {
- AlertDialog.Builder builder = new AlertDialog.Builder(SPActivity.this);
- builder.setIcon(R.drawable.icon);
- builder.setTitle(string);
- builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- finish();
- }
- });
- builder.show();
- }
- }
對應的 XML 佈局如下:
- <?xml version="1.0" encoding="utf-8"?>
-
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical"
- >
- <ImageView android:id="@+id/sp_image"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/image"
- android:layout_gravity="center"
- />
- <EditText android:id="@+id/sp_et0"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:hint="請輸入你的姓名">
- </EditText>
- <EditText android:id="@+id/sp_et1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:hint="請輸入你的號碼">
- </EditText>
- <Button android:id="@+id/sp_button0"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="保存輸入內容shared">
- </Button>
- <Button android:id="@+id/sp_button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="清除shared保存內容">
- </Button>
- <Button android:id="@+id/sp_button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="刪除shared文件">
- </Button>
- </LinearLayout>
二、在 data 目錄下以自訂檔案處理數據
如果不希望把資料存在 SharedPreferences 中,我們也可以自行建立一個檔案來保存所需的資料。這裡選擇將檔案存放在系統的工程路徑下。
先輸入需要保存的內容:

保存完成後,紅框內會顯示上一次保存的資料:

保存之後,檔案會被存放到當前工程下 files 資料夾的路徑中。這裡要特別提醒:data 資料夾在手機未取得 root 權限時,一般使用者是無法直接存取的。這種方式有一個較為麻煩的地方——檔案中的資料需要由程式設計師自行解析處理。舉例來說,若檔案中保存了大量字串,而你只需要其中一部分,就必須自己撰寫程式碼,從檔案中擷取所需的內容。

Java 程式碼:
- public class FileActivity extends Activity {
- public final static String FILE_NAME = "a.txt";
-
- /**File中儲存數據的路徑**/
- public final static String DATA_URL = "/data/data/";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- setContentView(R.layout.file);
- /**讀取內容**/
- String content = loadFile();
- if(content == null) {
- content = "上次沒有輸入內容請輸入";
- }
- String str = "上次輸入保存的內容的姓名為【 " +content + "】";
- final EditText editContent = ((EditText)findViewById(R.id.file_et0));
- editContent.setHint(str);
- Button button0 = (Button)findViewById(R.id.file_button0);
-
- /**監聽按鈕點擊後保存用戶輸入信息到file中**/
- button0.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- /**拿到用戶輸入的信息**/
- String content = editContent.getText().toString();
- /**開始保存入file**/
- saveFile(content);
- ShowDialog("保存File文件成功");
- }
- });
-
- Button button1 = (Button)findViewById(R.id.file_button1);
- /**監聽按鈕點擊後清空file中內容**/
- button1.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- cleanFile();
- ShowDialog("清空File文件成功");
- }
- });
-
- Button button2 = (Button)findViewById(R.id.file_button2);
-
- /**監聽按鈕點擊後刪除file文件**/
- button2.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- File file = new File(DATA_URL + getPackageName().toString()
- + "/files", FILE_NAME);
- if (file.exists()) {
- file.delete();
- }
- ShowDialog("刪除file文件成功");
- }
- });
-
- super.onCreate(savedInstanceState);
- }
-
- /**
- * 保存內容
- * @param str
- */
- public void saveFile(String str) {
- try {
- FileOutputStream outStream = this.openFileOutput(FILE_NAME,
- Context.MODE_WORLD_READABLE);
- outStream.write(str.getBytes());
- outStream.close();
- } catch (FileNotFoundException e) {
- } catch (IOException e) {
- }
- }
-
- /**
- * 因為java刪除文件內容只有一種實現方法,就是把整個文件重寫,只是把須要刪除的那一條記錄去除掉
- */
- public void cleanFile() {
- //如果只須要刪除文件中的一部分內容則須要在這裡對字符串做一些操作
- String cleanStr = "";
- try {
- FileOutputStream outStream = this.openFileOutput(FILE_NAME,
- Context.MODE_WORLD_READABLE);
- outStream.write(cleanStr.getBytes());
- outStream.close();
- } catch (FileNotFoundException e) {
- } catch (IOException e) {
- }
-
- }
-
- public String loadFile() {
- try {
- FileInputStream inStream = this.openFileInput(FILE_NAME);
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int length = -1;
- while ((length = inStream.read(buffer)) != -1) {
- stream.write(buffer, 0, length);
- }
- stream.close();
- inStream.close();
- return stream.toString();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- }
- return null;
- }
-
- public void ShowDialog(String str) {
- AlertDialog.Builder builder = new AlertDialog.Builder(FileActivity.this);
- builder.setIcon(R.drawable.icon);
- builder.setTitle(str);
- builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- finish();
- }
- });
- builder.show();
- }
- }
XML 佈局:
- <?xml version="1.0" encoding="utf-8"?>
-
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical"
- >
- <ImageView android:id="@+id/file_image"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/jay"
- android:layout_gravity="center"
- />
-
- <EditText android:id="@+id/file_et0"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:hint="請輸入需要保存的內容">
- </EditText>
- <Button android:id="@+id/file_button0"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="保存入file">
- </Button>
- <Button android:id="@+id/file_button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="清除file保存內容">
- </Button>
- <Button android:id="@+id/file_button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="刪除file文件">
- </Button>
- </LinearLayout>
三、在 res/raw 目錄中讀取數據
Android 提供了專門讀取 res/raw 路徑下資源的方法,但並未提供寫入的介面,也就是說 raw 中的內容只能讀、不能寫。在實際開發中,我們有時需要讀取大量的文字資源,而這些文字在應用運行期間不會發生改變,無需重新寫入或修改,因此可以透過 raw 來操作這類數據。
下圖展示了在清單中讀取 .bin 檔案內容並逐行顯示於 listView 的效果:

如下圖所示,raw 路徑下存放了一個名為 date0.bin 的檔案,下面我們需要讀取該 .bin 檔案的內容並顯示在螢幕上。

以下是程式碼實現:
- public class loadRawActivity extends ListActivity {
-
- private class MyListAdapter extends BaseAdapter {
- private int[] colors = new int[] { 0xff626569, 0xff4f5257 };
-
- public MyListAdapter(Context context) {
- mContext = context;
- }
-
- public int getCount() {
- return inpormation.length;
- }
-
- @Override
- public boolean areAllItemsEnabled() {
- return false;
- }
-
- public Object getItem(int position) {
- return position;
- }
-
- public long getItemId(int position) {
- return position;
- }
-
- public View getView(int position, View convertView, ViewGroup parent) {
- TextView tv;
- if (convertView == null) {
- tv = (TextView) LayoutInflater.from(mContext).inflate(
- android.R.layout.simple_list_item_1, parent, false);
- } else {
- tv = (TextView) convertView;
- }
- int colorPos = position % colors.length;
- tv.setBackgroundColor(colors[colorPos]);
- tv.setText(String.valueOf(position + 1) + ":"
- + inpormation[position]);
- return tv;
- }
-
- private Context mContext;
- }
-
- String[] inpormation = null;
- ListView listView;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- readFile(R.raw.date0);
- setListAdapter(new MyListAdapter(this));
- listView = getListView();
- int[] colors = { 0, 0xFF505259, 0 };
- listView
- .setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
- listView.setDividerHeight(10);
- super.onCreate(savedInstanceState);
- }
-
- /**
- * 從raw中讀取數據
- * @param ID
- */
- public void readFile(int ID) {
- InputStream in = null;
- String temp = "";
- try {
- in = this.getResources().openRawResource(ID);
- byte[] buff = new byte[1024];// 緩存
- int rd = 0;
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- while ((rd = in.read(buff)) != -1) {
- baos.write(buff, 0, rd);
- temp = new String(baos.toByteArray(), "UTF-8");
- }
- baos.close();
- in.close();
- inpormation = temp.split("\r\n");
- } catch (Exception e) {
- Toast.makeText(this, "文件沒有找到", 2000).show();
- }
- }
-
- }
四、在 SD 卡中處理數據
我們也可以把數據保存在 SD 卡中,做法是在 SD 卡上建立一個檔案來存放資料。需要說明的是,SD 卡是使用者可以直接存取的,因此適合存放一些可有可無的數據——即使使用者刪除了卡中的內容,也不會影響軟體的正常使用。


Java 程式碼:
- public class loadSDActivity extends Activity {
- public final static String FILE_NAME = "b.txt";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- setContentView(R.layout.sdfile);
- /**讀取內容**/
- String content = loadFile();
- if(content == null) {
- content = "上次沒有輸入內容請輸入";
- }
-
- final EditText editContent = (EditText)findViewById(R.id.sdfile_et0);
- editContent.setHint("上次輸入SD卡的內容的為【 " +content + "】");
- Button button0 = (Button)findViewById(R.id.sdfile_button0);
-
- /**監聽按鈕點擊後保存用戶輸入信息到SD卡中**/
- button0.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View arg0) {
- /**拿到用戶輸入的信息**/
- String content = editContent.getText().toString();
- /**開始保存入SD卡**/
- saveFile(content);
- ShowDialog("保存SD卡文件成功");
- }
- });
- Button button1 = (Button)findViewById(R.id.sdfile_button1);
-
- /**去清除SD卡保存的內容**/
- button1.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- cleanFile();
- ShowDialog("清除SD卡文件中的內容成功");
- }
- });
- Button button2 = (Button)findViewById(R.id.sdfile_button2);
-
- /**刪除SD卡保存的文件**/
- button2.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- DeleteSDFile();
- }
- });
-
- super.onCreate(savedInstanceState);
- }
-
- /**
- * 保存入SD卡中
- * @param str
- */
- public void saveFile(String str) {
- FileOutputStream fileOutputStream = null;
-
- File file = new File(Environment.getExternalStorageDirectory(),
- FILE_NAME);
- try {
- fileOutputStream = new FileOutputStream(file);
- fileOutputStream.write(str.getBytes());
- fileOutputStream.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 讀取SD卡的內容
- * @return
- */
- public String loadFile() {
- String path = Environment.getExternalStorageDirectory() + "/" + FILE_NAME;
- try {
-
- FileInputStream fi = new FileInputStream(path);
- BufferedReader br = new BufferedReader(new InputStreamReader(
- fi));
- String readString = new String();
- while ((readString = br.readLine()) != null) {
- //數據多的話須要在這裡處理 readString
- return readString;
- }
- fi.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return null;
- }
-
- /**
- * 刪除SD卡
- */
- public void DeleteSDFile() {
- String path = Environment.getExternalStorageDirectory() + "/"
- + FILE_NAME;
- File file1 = new File(path);
- boolean isdelte = file1.delete();
- if(isdelte) {
- ShowDialog("刪除SD卡成功");
- }else {
- finish();
- }
- }
-
- /**
- * 因為java刪除文件內容只有一種實現方法,就是把整個文件重寫,只是把須要刪除的那一條記錄去除掉
- */
- public void cleanFile() {
- //如果只須要刪除文件中的一部分內容則須要在這裡對字符串做一些操作
- String cleanStr = "";
- FileOutputStream fileOutputStream = null;
-
- File file = new File(Environment.getExternalStorageDirectory(),
- FILE_NAME);
- try {
- fileOutputStream = new FileOutputStream(file);
- fileOutputStream.write(cleanStr.getBytes());
- fileOutputStream.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }catch (IOException e) {
- e.printStackTrace();
- }
- }
- public void ShowDialog(String str) {
- AlertDialog.Builder builder = new AlertDialog.Builder(loadSDActivity.this);
- builder.setIcon(R.drawable.icon);
- builder.setTitle(str);
- builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- finish();
- }
- });
- builder.show();
- }
- }
XML 佈局:
- <?xml version="1.0" encoding="utf-8"?>
-
- <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical"
- >
- <ImageView android:id="@+id/sdfile_image"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/g"
- android:layout_gravity="center"
- />
- <EditText android:id="@+id/sdfile_et0"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:hint="請輸入需要保存到SD卡的內容">
- </EditText>
- <Button android:id="@+id/sdfile_button0"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="保存輸入內容到SD卡">
- </Button>
- <Button android:id="@+id/sdfile_button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="清除SD卡保存文件的內容">
- </Button>
- <Button android:id="@+id/sdfile_button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="刪除SD卡中保存的文件">
- </Button>
- </LinearLayout>
以上就是四種常見本地數據儲存方案的完整示範。掌握它們各自的適用場景,你就能在開發中為每一類數據選擇最合適的存放方式。原始碼下載地址:https://vdisk.weibo.com/s/a9n91