Android开发中有五种数据持久化API:
data/data/<包名>/ | 描述 |
---|---|
Context#getDir(String name,int mode):File! | 内部存储根目录下的文件夹(不存在则新建) |
data/data/<包名>/files/ | 描述 |
---|---|
Context#getFilesDir():File! | files文件夹 |
Context#fileList():Array<String!>! | 列举文件和文件夹 |
Context#openFileInput(String name):FileInputStream! | 打开文件输入流(不存在则抛出FileNotFoundException) |
Context#openFileOut(String name,int mode):FileOutputStream! | 打开文件输出流(文件不存在则新建) |
Context#deleteFile(String name):Boolean! | 删除文件或文件夹 |
data/data/<包名>/cache/ | 描述 |
---|---|
Context#getCacheDir():File! | cache文件夹 |
data/data/<包名>/code_cache/ | 描述 |
---|---|
Context#getCodeCacheDir():File! | 存放优化过的代码(如JIT优化) |
data/data/<包名>/no_backup/ | 描述 |
---|---|
Context#getNoBackUpFIlesDir():File! | 在Backup过程中被忽略的文件 |
// 举例(targetSdkVersion >= 24):
try(FileOutputStream fos = openFileOutput("file_name",MODE_WORLD_WRITEABLE)){
fos.write("Not sensitive information".getBytes());
}catch (IOException e){
e.printStackTrace();
}
// 异常:
Caused by: java.lang.SecurityException: MODE_WORLD_READABLE no longer supported
Caused by: java.lang.SecurityException: MODE_WORLD_WRITEABLE no longer supported
早期的Android设备存储空间较小,有一个内置(build-in)的存储空间,即内部存储,另外还有一个可以移除的存储介质,即外部存储(如SD卡)。但是随着设备内置存储空间增大,很多设备已经足以将内置存储空间一分为二,一块为内部存储,一块为外部存储。
外部存储并不总是可用的,因为外部存储可以移除(早期设备)或者作为USB存储设备连接到PC,访问前必须检查是否挂载(mounted):
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
/* 检查外部存储是否可读写 */
void updateExternalStorageState() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// 可读写
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// 可读
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
}
BroadcastReceiver mExternalStorageReceiver;
/* 开始监听 */
void startWatchingExternalStorage() {
mExternalStorageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 更新状态
updateExternalStorageState();
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
// 动态注册广播接收器
registerReceiver(mExternalStorageReceiver, filter);
updateExternalStorageState();
}
/* 停止监听 */
void stopWatchingExternalStorage() {
// 注销广播接收器
unregisterReceiver(mExternalStorageReceiver);
}
storage/emulated/0/Android/
因为外部存储不一定可用,所以返回值可为空或空数组
storage/emulated/0/ | 描述 |
---|---|
Environment.getExternalStorageDirectory():File? | 外部存储根目录 |
Environment.getExternalStoragePublicDirectory(name:String?):File? | 外部存储根目录下的文件夹 |
Environment.getExternalStorageState():String! | 外部存储状态 |
storage/emulated/0/Android/data/<包名>/ | 描述 |
---|---|
Context.getExternalCacheDir():File? | cache文件夹 |
Context.getExternalCacheDirs():Array<File!>! | 多部分cache文件夹(API 18) |
Context.getExternalFilesDir(type: String?):File? | files文件夹 |
Context.getExternalFIlesDirs(type:String?):Array<File!>! | 多部分files文件夹(API 18) |
Context.getExternalMediaDirs():Array<File!>! | 多部分多媒体文件夹(API 21) |
有些设备可以外接存储设备(如SD卡)来获得更大的外部存储空间,相当于有多部分外部存储空间,一块内置,一块外置。在存储空间足够时,应该优先存储在内置的部分。
> 兼容:Context.getExternalFilesDirs():Arra<File!>!,在低版本中数组只会返回一个元素,指向内置的外置存储的路径
版本变更:外部存储多媒体文件夹——Context.getExternalMediaDirs()(API 21
):对MediaScanner
可见
StorageManager sm = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
UUID uuid = sm.getUuidForPath(getCacheDir());
long byteSize = sm.getCacheQuotaBytes(uuid);
sm.getCacheSizeBytes(uuid)
// 整个文件夹视为一个缓存整体,在系统回收空间时清空文件夹sm.setCacheBehaviorGroup(dirFile,true)
// 在系统回收文件时,清空文件数据(length=0),而不是直接删除文件sm.setCacheBehaviorTombstone(dirFile,true)
> 漏洞:应用可以设置文件修改时间到一个稍晚的时间(比如2050年),保持不被删除
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tencent.tmgp.sgame"
platformBuildVersionCode="28"
platformBuildVersionName="9"
android:compileSdkVersion="28"
android:compileSdkVersionCodename="9"
android:installLocation="auto"
android:theme="@android:style/Theme.NoTitleBar">
val target = File(context.filesDir,"my-download")
target.freeSpace // 未分配容量(Root用户可用的容量)
target.usableSpace // 可用容量(非Root用户可用的容量)
target.totalSpace // 全部容量(包括已分配容量和未分配容量)
val target = File(context.filesDir,"my-download")
val stat = StatFs(target)
val blockSize = stat.blockSizeLong
stat.freeBlocksLong * blockSize // 同上
stat.availableBlocksLong * blockSize // 同上
stat.blockCountLong * blockSIze // 同上
val target = File(context.filesDir,"my-download")
val ssm = getSystemService(Context.STORAGE_STATS_SERVICE) as StorageStatsManager
val sm = getSystemService(Context.STORAGE_SERVICE) as StorageManager
val uuid = sm.getUuidForPath(target)
ssm.getFreeBytes(uuid) // 可用容量(非Root用户可用的容量)
ssm.getTotalBytes(uuid) // 完整的物理容量(比如64G)
```
val target = File(context.filesDir,"my-download")val ssm = getSystemService(Context.STORAGE_STATS_SERVICE) as StorageStatsManagerval sm = getSystemService(Context.STORAGE_SERVICE) as StorageManagerval uuid = sm.getUuidForPath(target)ssm.getFreeBytes(uuid) // 可用容量(非Root用户可用的容量)ssm.getTotalBytes(uuid) // 完整的物理容量(比如64G)
```
> 注意:即使判断磁盘空间充足,也可能在写入过程中抛出IOException(空间不足),因为无法避免多线程或多进程并发写入。
val target = File(context.filesDir,"my-download")
val sm = getSystemService(Context.STORAGE_SERVICE) as StorageManager
val uuid = sm.getUuidForPath(target)
if(downloadSize <= sm.getAllocatableBytes(uuid){
try(FileOutPutStream os = FileOutPutStream(target)){
// 预分配downloadSize大小的空间给当前应用
sm.allocateBytes(os.getFD(),downloadSize)
// 写入
...
}
}else{
// 空间不足,请求用户自行清理空间
val intent = Intent(StorageManager.ACTION_MANAGE_STORAGE);
intent.putExtra(StorageManager.EXTRA_UUID,uuid);
// 需要的空间
intent.putExtra(StorageManager.EXTRA_REQUESTED_BYTES,downloadSize);
context.tartActivityForResult(intent,REQUEST_CODE);
}
> StorageManager#allocateBytes()可以避免了并发写入造成空间不足异常
| 位置 | 其他应用 | 未root用户 | root用户 | MediaScanner |
| --- | --- | --- | --- | --- |
| 内部存储 | X | X | √ | X |
| 私有内部存储 | √ | √ | √ | 仅多媒体文件夹 |
| 公共内部存储 | √ | √ | √ | √ |
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有