Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 資料保存方式總整理:SharedPreferences、內部儲存、SD 卡與 SQLite

編輯:關於 Android 程式設計

SharedPreferences:輕量鍵值儲存

SharedPreferences 適合保存設定值、計數器或小型狀態。資料會以 XML 形式存放在應用程式私有目錄,預設僅供本程式存取。讀取時透過 getSharedPreferences 取得物件,寫入時則使用 Editor 的 put 系列方法,最後呼叫 commit 或 apply 提交。

SharedPreferences share = getSharedPreferences("share", Context.MODE_PRIVATE);
Editor editor = share.edit();
editor.putInt("count", 1);
editor.commit();

內部儲存:檔案輸入與輸出

若需要保存較長的文字或自訂格式資料,可使用 openFileOutput 與 openFileInput。檔案會放在應用程式專屬的內部儲存空間,適合保存不需要對外公開的資料。

FileOutputStream out = openFileOutput("test.txt", MODE_APPEND);
out.write(content.getBytes());
out.close();

SD 卡與外部儲存

寫入外部儲存前,必須先確認權限與掛載狀態。可透過 Environment.getExternalStorageState() 判斷是否可讀寫,再用 getExternalStorageDirectory() 取得路徑。實務上若要上架新版 Android,還需留意分流儲存與權限模型的差異。

SQLite:結構化資料庫

SQLite 適合保存大量結構化資料。常見流程是以 openOrCreateDatabase 建立或開啟資料庫,再用 execSQL 執行建表或新增,用 rawQuery 查詢並取得 Cursor。完成操作後應關閉資料庫與 Cursor,避免資源浪費。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved