zoukankan      html  css  js  c++  java
  • 转:Android文件存储路径getFilesDir()与getExternalFilesDir的区别

    作为一个开发者,我们经常需要通过缓存一些文件到SD卡中,常见的方式就是,通过:

    File sdCard = Environment.getExternalStorageDirectory();

    获取SD卡根目录,然后自定义文件/文件名进行文件存储.这样做法的结果就是,当手机安装了大量的app时,

    SD卡根目录会迅速变得杂乱不堪。并且在API 6.0之后,根目录文件存储是需要用户授权的,就算你在

    AndroidManifest.xml中配置了存储权限,用户不授权也是写不进去了.

    SD卡读写权限:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    其实,Google已经提供了最佳的外部存储方案,那就是统一路径为:

    /Android/data/< package name >/files/… (该路径通常挂载在/mnt/sdcard/下)

    外部存储路径调用方法是:context.getExternalFilesDir(dir).getAbsolutePath() //通过context调用,

    参数dir为自自定义文件夹.

    这个方法获得的文件存储路径适用于6.0以后系统,主要AndroidManifest.xml配置读写权限了,

    就不需要用户再授权了.

    以上,是关于外部存储的介绍,那么如果有些手机没有SD卡或者系统自身没有分配外部存储空间,时,

    我们应该怎么缓存数据呢?

    那就需要用到内部存储了,内部存储的路径是: /data/data/< package name >/files/…

    (该路径挂载在在手机自身存储目录)

    内部存储路径调用方法是:context().getCacheDir().getAbsolutePath() //通过context调用

    因此,正常开发中获取存储路径的方法是:

    /**
    * 
    * @param context 上下文对象
    * @param dir  存储目录
    * @return
    */
    public static String getFilePath(Context context,String dir) {
    String directoryPath="";
    //判断SD卡是否可用 
    if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ) {
    directoryPath =context.getExternalFilesDir(dir).getAbsolutePath() ;  
    // directoryPath =context.getExternalCacheDir().getAbsolutePath() ;  
    }else{
    //没内存卡就存机身内存  
    directoryPath=context.getFilesDir()+File.separator+dir;
    // directoryPath=context.getCacheDir()+File.separator+dir;
    }
    File file = new File(directoryPath);  
    if(!file.exists()){//判断文件目录是否存在  
    file.mkdirs();  
    } 
    LogUtil.i("filePath====>"+directoryPath);
    return directoryPath;
    }

    其中,getExternalCacheDir()与getCacheDir()的区别 与getExternalFilesDir()及getFilesDir()的区别相同,

    前者只是在路径下自动建好了一个cach文件目录:/data/< package name >/files/cach/...

    存储区别简明示意图如下:

    本文转自:https://blog.csdn.net/losefrank/article/details/53464646

  • 相关阅读:
    2019年面试题1
    面试题
    vsftp多个用户公享同一个文件,但是权限不同
    centos7搭建ftp
    安装v2ra y
    centos7安装lamp
    日升昌面试题
    一些插件
    面试被怼集(字节跳动篇)
    TOMCAT原理详解及请求过程(转载)
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/10332808.html
Copyright © 2011-2022 走看看