編輯于2016年
內(nèi)部存儲
preferences保存
//保存數(shù)據(jù)到文件
//多個preferences時實(shí)用命名讀取和創(chuàng)建// SharedPreferences sharedPreferences = getSharedPreferences("bartest",this.MODE_PRIVATE);
//只有一個preference時
SharedPreferences preference = getPreferences(this.MODE_PRIVATE);//獲取編輯句柄 SharedPreferences.Editor editor = preference.edit();editor.putString("userName","krock");
editor.commit();// 完成保存
//讀取數(shù)據(jù)
// String userName = preference.getString("userName","app");
文件保存
//簡單的一個寫入文件步驟
String filename = "myfile";String word = "hello World";
FileOutputStream fileOutputStream;
try{fileOutputStream = openFileOutput(filename,this.MODE_PRIVATE);
fileOutputStream.write(word.getBytes());
fileOutputStream.close();
}catch (Exception ex){
ex.getStackTrace();
}
//緩存空間存儲
file = File.createTempFile(fileName, null, context.getCacheDir());
外部存儲
獲取存儲卡狀態(tài)
/* 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;}
創(chuàng)建公共文件
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;}
創(chuàng)建私有文件
文件會在用戶卸載我們的app時被系統(tǒng)刪除
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;}
獲取剩余空間
刪除文件
在不需要使用某些文件的時候應(yīng)刪除它。刪除文件最直接的方法是直接執(zhí)行文件的delete()
方法寇僧。
myFile.delete();
如果文件是保存在internal storage摊腋,我們可以通過Context
來訪問并通過執(zhí)行deleteFile()
進(jìn)行刪除
myContext.deleteFile(fileName);