日常的开发中总是会遇到需要缓存一些文件到本地,一直以来对获取缓存路径的几个方法对应的路径一直有点迷糊,有空小结一下几个方法对应的路径
String CacheFilePath =getCacheDir().getAbsolutePath();
String ExternalCacheFilePath = getExternalCacheDir().getAbsolutePath();
String ExternalStorageFilePath =Environment.getExternalStorageDirectory().getAbsolutePath();
File CacheFile = new File(CacheFilePath,"CacheDir.txt");
File ExternalCacheFile = new File(ExternalCacheFilePath,"ExternalCacheDir.txt");
File ExternalStorageFile = new File(ExternalStorageFilePath,"ExternalStorage.txt");
try {
if (CacheFile.createNewFile()){
Log.e("FileTest","CacheFile is created :" + CacheFile.getAbsolutePath());
}else if (CacheFile.exists()){
Log.e("FileTest","CacheFile is created :" + CacheFile.getAbsolutePath());
}
if (ExternalCacheFile.createNewFile()){
Log.e("FileTest","ExternalCacheFile is created " + ExternalCacheFile.getAbsolutePath())
}else if (ExternalCacheFile.exists()){
Log.e("FileTest","ExternalCacheFile is created " + ExternalCacheFile.getAbsolutePath());
}
if (ExternalStorageFile.createNewFile()){ //NEED PERMISSION
Log.e("FileTest","ExternalStorageFile is created :" + ExternalStorageFile.getAbsolutePath());
}else if (ExternalStorageFile.exists()){
Log.e("FileTest","ExternalStorageFile is created :" + ExternalStorageFile.getAbsolutePath());
}
} catch (IOException e) {
e.printStackTrace();
}
分别对应三个方法:
getCacheDir()
getExternalCacheDir()
Environment.getExternalStorageDirectory()
三个目录的区别
方法 | 类别 | 权限 | 路径 | 备注 |
---|---|---|---|---|
context.getCacheDir() | 内部存储 | 无需权限 | data/data/包名/cache | 卸载应用后会自动删除 |
context.getExternalCacheDir() | 外部存储 | 无需权限 | Android/data/包名/cache | 卸载应用后会自动删除 |
getExternalFilesDir(String type) | 外部存储 | 无需权限 | Android/data/包名/files | 如果传入非空的String 会在其目录下创建相应文件夹比如传入“test”就是Android/data/包名/files/test;卸载应用后会自动删除 |
Environment.getExternalStorageDirectory() | 外部存储 | 需要权限 | SD卡或者外部存储根路径 | 卸载应用后仍然存在 |
并且处于内部存储的路径data/data 我们在手机上的文件管理器上是看不到的,在AS上右下角靠边这里的文件管理可以看到
private static Uri getUriForFile(Context context, File file) {
if (context == null || file == null) {//简单地拦截一下
throw new NullPointerException();
}
Uri uri;
if (Build.VERSION.SDK_INT >= 24) {
uri = FileProvider.getUriForFile(context, "com.hjl.android7.fileprovider", file);
} else {
uri = Uri.fromFile(file);
}
return uri;
}
public File uri2File(Uri uri) { return new File(uri.getPath()); }
public Bitmap File2Bitmap(String filePath){
File file = new File(filePath);
Uri uri = Uri.fromFile(file);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), uri);
}
public static boolean writeBitmapToFile(Bitmap bitmap, File file, int quality){
boolean flag = false;
try {
FileOutputStream fos = new FileOutputStream(file);
flag = bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
适配7.0,Android 打开相册、拍照、裁剪图片的用法、细节处理