Android之數據儲存001
- 001篇總結了SharedPreferences和File的使用秃殉。
Android中的數據儲存主要包括如下幾項:
- 在SharedPreferences中保存簡單數據類型的鍵值對
- 在Android的文件系統(tǒng)在保存任意文件秩仆,即通過file來保存數據
- 使用SQLite數據庫來持久化數據
SharedPreferences
- Android中SharedPreferences API用于輕量級簡單數據類型的數據保存
- 一般保存APP配置脆霎,用戶設置榜配,是否登錄
- 獲取SharedPreferences對象愿待,用于讀取數據
<pre>
<code> Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
</code>
</pre> - 向SharedPreferences中存入數據硝皂,使用SharedPreferences.Editor對象盯另。
<pre>
<code>
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
</code>
</pre>
- 注意:editor.commit()方法一定要調用,不然寫入數據無效兄一。
使用File API來保存數據
關于File存儲
- File對象適合從開始到結束的順序讀取和寫入大量數據厘线。
- 比如,它適合圖像文本文件出革,視頻音頻文件或者通過網絡交換的任何內容造壮。
- 與Java中的File IO系統(tǒng)有點相似。
選擇內部或者外部存儲
所有的Android設備都有兩個文件存儲區(qū)域:內部存儲或者外部存儲骂束,外部存儲常見的是外置SD卡耳璧。
內部存儲:
- 始終可用
- 默認情況下只有您的應用可以訪問此處保存的文件
- 當您的應用卸載的時候,數據也自動刪除
- 當你希望確保用戶或者其他應用均無法訪問您的文件時展箱,內部存儲是最佳選擇旨枯。
外部存儲
- 并非始終可用,當SD卡壞掉或者被移除的時候無法使用
- 是全局可讀的混驰,比如下載的視頻可用被很多播放器所打開
- 當用戶卸載應用的時候攀隔,只有您通過getExternalFilesDir()將您的應用的文件保存在目錄中時,系統(tǒng)才會刪除文件
- 對于栖榨,無需訪問限制而且希望與其他應用共享比如視頻文本照片昆汹,外部存儲是最佳的選擇。
- 外部存儲需要獲取存儲權限:
<code>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>
如果您的應用需要讀取外部存儲婴栽,需要添加權限:
<code>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>
將文件保存在內部存儲中
- getFilesDir():返回您的應用的內部目錄的File
- getCacheDir():返回您的應用的緩存文件的內部目錄的File满粗。
- 注意:務必刪除所有不再需要的文件并合理制定緩存文件的大小,比如1MB愚争。因為在系統(tǒng)內存不足的情況下映皆,它將會在不進行警告的情況下刪除您的緩存文件。
- 要在這些目錄中新建一些文件准脂,可以使用File()構造函數劫扒,傳遞指定您的應用內部文件目錄和想創(chuàng)建的文件名。然后打開流寫入數據狸膏。
<code>
File file = new File(context.getFilesDir(),filename);
</code> - 看個寫入數據的例子:
<pre><code>
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
</code>
</pre>
- 獲取應用的內部緩存沟饥,獲取之后就能寫入緩存數據
<pre>
<code>
public File getTempFile(Context context, String url) {
File file;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
catch (IOException e) {
// Error while creating file
}
return file;
}
</code>
</pre>
將文件保存在外部存儲中
- 第一步:判斷Android是否具有外部存儲空間,即是否具有SD卡湾戳,以及SD卡是否具有空間贤旷。
<pre>
<code>
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
</code>
</pre>
- 如果能夠讀取和寫入外部文件,那么需要考慮的是:可以保存兩類文件:
- 公共文件:可以供其他應用和用戶使用的文件砾脑,應用卸載后仍然可以使用這些文件幼驶。
- 私有文件:本屬于您的應用且用戶卸載時刪除的文件。實際上不向您的應用之外的用戶提供值的文件韧衣,但注意:因為存在外部存儲上仍有技術可以被其他應用獲取使用盅藻。
- 獲取公共存儲文件目錄方法:getExternalStoragePublicDirectory()
- 獲取私有外部存儲文件目錄:getExternalFilesDir()购桑,通過此方法創(chuàng)建的各目錄位于封裝您應用的所有外部存儲文件的父目錄,應用卸載時氏淑,系統(tǒng)會刪除這些文件勃蜘。
- 看代碼:第一個為創(chuàng)建公共相冊第二個為創(chuàng)建私有個人相冊:
- 公有相冊
<pre>
<code>
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
</code>
</pre> - 私有相冊
<pre>
<code>
public File getAlbumStorageDir(Context context, String albumName) {
// Get the directory for the app's private pictures directory.
File file = new File(context.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
</code>
</pre>
- 公有相冊
查詢可用空間
注意:在保存文件之前,您無需查詢可用空間量假残。當空間不足而你再寫入文件時會出現IOException缭贡,將其捕獲進行處理就ok了。
刪除文件:
- 刪除文件最直接方式辉懒,是獲取file對象阳惹,調用其的delete方法,如:
myFile.delete(); - 如果文件保存在內部存儲中眶俩,還可以使用Context的deleteFile來定位和刪除文件莹汤,比如:
mContext.deleteFile(fileName); - 當存在內部存儲和私有的外部存儲時,當應用被卸載的時候仿便,數據會被自動刪除体啰。
- 另外應該手動刪除使用getCacheDir()的所有的緩存文件和定期刪除其他不需要的文件攒巍。