一、内部存储(internal storage)和外部存储(external storage)的比较:
2.当用户卸载你的软件时,该软件存储在内存的所有文件会被移除,对于存储在sd卡的文件,只能移除通过getExternalFilesDir()
获取的文件夹下的文件;
3.读写内存不需要权限,读写sd卡需要相应权限。
二.向内存存储:
通过getFilesDir()或者getCacheDir()获得一个代表内存目录的File对象,要在这个目录下创建文件,可以调用File对象的相应构造方法,
如:
File file = new File(context.getFilesDir(), filename);
也可以通过openFileOutput()获得一个FileOutputStream对象来向内存中的某个文件写入数据,如:
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();
}
还可以通过openFileInput()方法获取FileInputStream,用来向内存中某个文件写入数据。
如果需要缓存一些文件,则可以调用createTempFile()方法,如:
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;
}
三、向sd卡存储:
每次向sd卡读写数据时,都要判断其是否可用,如:
/* 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;
}
在sd卡中有两种类型的文件种类:一种是可以被任意app访问的,当卸载软件时不会删除;一种是app所私有的,当卸载软件时一并删除。
要获取可以任意访问类型的文件,调用 getExternalStoragePublicDirectory()方法返回一个文件夹,如:
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;
}
第一个参数指定你要存储的文件类型,如 DIRECTORY_MUSIC, DIRECTORY_RINGTONES,也可以为空。要获取为你的app所私有的文件,调用 getExternalFilesDir()方法,如:
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;
}
注:一些设备可能在手机的内存中分出部分空间作为external storage,如果此设备运行在Android4.3或更早的
版本上, getExternalFilesDir()只会返回对应的使用内存的文件夹,而不会在sd卡上存储数据,而在Android4.4版本之后,可以通过调用
getExternalFilesDirs()获取一个外部存储文件夹数组,该数组的第一个元素对应sd卡下的文件夹。
在sd卡上缓存文件:
调用getExternalCacheDir(),该文件夹也存在上述问题,可以通过调用 getExternalCacheDirs()解决。
四、获取可用空间
调用getFreeSpace()和getTotalSpace()方法。