编辑于2016年
内部存储
preferences保存
//保存数据到文件
//多个preferences时实用命名读取和创建// 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();// 完成保存
//读取数据
// 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());
外部存储
获取存储卡状态
/* 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;}
创建公共文件
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;}
创建私有文件
文件会在用户卸载我们的app时被系统删除
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;}
获取剩余空间
删除文件
在不需要使用某些文件的时候应删除它。删除文件最直接的方法是直接执行文件的delete()
方法。
myFile.delete();
如果文件是保存在internal storage,我们可以通过Context
来访问并通过执行deleteFile()
进行删除
myContext.deleteFile(fileName);