26.2.2外部私用存储
内部存储的文件应该属于私有文件,别的APP想要访问是比较困难的;外部存储由于容量较大,一般是APP保存较大文件的不二选择,那么是不是外部存储里面的文件,所有的APP都可以随意访问呢?显然并不是这样的,在外部存储中,也存在着私有文件的概念。
就像在前面获取内部存储的方法一样,使用Context.getExternalCacheDir()和Context.getExternalFilesDir()就可以获取到外部存储的私有文件:
File file3 = new File(getExternalCacheDir().getAbsolutePath(), "getExternalCacheDir.txt");
try {
OutputStream outputStream1 = new FileOutputStream(file3);
outputStream1.write("getExternalCacheDir".getBytes());
outputStream1.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.d("TAG", "file3=" + file3);
File file4 = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "getExternalFilesDir.txt");
try {
OutputStream outputStream1 = new FileOutputStream(file4);
outputStream1.write("getExternalFilesDir".getBytes());
outputStream1.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.d("TAG", "file4=" + file4);
运行结果如下:
file3=/storage/sdcard/Android/data/demo6.qz.com.demo6/cache/getExternalCacheDir.txt
file4=/storage/sdcard/Android/data/demo6.qz.com.demo6/files/Pictures/getExternalFilesDir.txt
在系统中的位置如下:
从上图可以看出,创建的私有文件的地址是
/sdcard/Android/date/package_name下面,用户不能直接看见这些文件。
如果想缓存图片等比较耗空间的文件,推荐放在getExternalCacheDir()所在的文件下面,这个文件和getCacheDir()很像,都可以放缓存文件,在APP被卸载的时候,都会被系统删除,而且缓存的内容对其他APP是相对私有的。
但是,除此之外,还是有一些差别的:
Theplatform does not always monitor the space available in shared storage, and thusmay not automatically delete these files. Apps should always manage the maximumspace used in this location. Currently the only time files here will be deletedby the platform is when running onJELLY_BEAN_MR1or later
andisExternalStorageEmulated(File)returnstrue.
Sharedstorage may not always be available, since removable media can be ejected bythe user. Media state can be checked usinggetExternalStorageState(File).
Thereis no security enforced with these files. For example, any application holdingWRITE_EXTERNAL_STORAGEcanwrite to these files.
Context.getExternalFilesDir()和Context.getFilesDir()也是有区别的,但是在应用卸载的时候,也是会被删除的,用户也不能直接看见这些文件。
两者区别如下:
Sharedstorage may not always be available, since removable media can be ejected by theuser. Media state can be checked usinggetExternalStorageState(File).
Thereis no security enforced with these files. For example, any application holdingWRITE_EXTERNAL_STORAGEcanwrite to these files.
上面二个目录分别对应设置->应用->应用详情里面的“清除数据”与“清除缓存”选项。
网友评论