• 彻底了解android中的内部存储与外部存储


    彻底了解android中的内部存储与外部存储
    我们先来考虑这样一个问题:

    打开手机设置,选择应用管理,选择任意一个App,然后你会看到两个按钮,一个是清除缓存,另一个是清除数据,那么当我们点击清除缓存的时候清除的是哪里的数据?当我们点击清除数据的时候又是清除的哪里的数据?读完本文相信你会有答案。

    在android开发中我们常常听到这样几个概念,内存,内部存储,外部存储,很多人常常将这三个东西搞混,那么我们今天就先来详细说说这三个东西是怎么回事?

    内存,我们在英文中称作memory,内部存储,我们称为InternalStorage,外部存储我们称为ExternalStorage,这在英文中本不会产生歧义,但是当我们翻译为中文之后,前两个都简称为内存,于是,混了。

    那么究竟什么是内部存储什么是外部存储呢?

    首先我们打开DDMS,有一个File Explorer,如下:

    彻底理解android中的内部存储与外部存储0

    这里有三个文件夹需要我们重视,一个是data,一个是mnt,一个是storage,我们下面就详细说说这三个文件夹。


    1.内部存储

    data文件夹就是我们常说的内部存储,当我们打开data文件夹之后(没有root的手机不能打开该文件夹),里边有两个文件夹值得我们关注,如下:

    一个文件夹是app文件夹,还有一个文件夹就是data文件夹,app文件夹里存放着我们所有安装的app的apk文件,其实,当我们调试一个app的时候,可以看到控制台输出的内容,有一项是uploading .....就是上传我们的apk到这个文件夹,上传成功之后才开始安装。另一个重要的文件夹就是data文件夹了,这个文件夹里边都是一些包名,打开这些包名之后我们会看到这样的一些文件:

    1.data/data/包名/shared_prefs
    2.data/data/包名/databases
    3.data/data/包名/files

    4.data/data/包名/cache

    如果打开过data文件,应该都知道这些文件夹是干什么用的,我们在使用sharedPreferenced的时候,将数据持久化存储于本地,其实就是存在这个文件中的xml文件里,我们App里边的数据库文件就存储于databases文件夹中,还有我们的普通数据存储在files中,缓存文件存储在cache文件夹中,存储在这里的文件我们都称之为内部存储。


    2.外部存储

    外部存储才是我们平时操作最多的,外部存储一般就是我们上面看到的storage文件夹,当然也有可能是mnt文件夹,这个不同厂家有可能不一样。

    一般来说,在storage文件夹中有一个sdcard文件夹,这个文件夹中的文件又分为两类,一类是公有目录,还有一类是私有目录,其中的公有目录有九大类,比如DCIM、DOWNLOAD等这种系统为我们创建的文件夹,私有目录就是Android这个文件夹,这个文件夹打开之后里边有一个data文件夹,打开这个data文件夹,里边有许多包名组成的文件夹。

    说到这里,我想大家应该已经可以分清楚什么是内部存储什么是外部存储了吧?好,分清楚之后我们就要看看怎么来操作内部存储和外部存储了。


    3.操作存储空间

    首先,经过上面的分析,大家已经明白了,什么是内部存储,什么是外部存储,以及这两种存储方式分别存储在什么位置,一般来说,我们不会自己去操作内部存储空间,没有root权限的话,我们也没法操作内部存储空间,事实上内部存储主要是由系统来维护的。不过在代码中我们是可以访问到这个文件夹的。由于内部存储空间有限,在开发中我们一般都是操作外部存储空间,Google官方建议我们App的数据应该存储在外部存储的私有目录中该App的包名下,这样当用户卸载掉App之后,相关的数据会一并删除,如果你直接在/storage/sdcard目录下创建了一个应用的文件夹,那么当你删除应用的时候,这个文件夹就不会被删除。

    经过以上的介绍,我们可以总结出下面一个表格:

    一目了然,什么是内部存储,什么是外部存储。

    如果按照路径的特征,我们又可以将文件存储的路径分为两大类,一类是路径中含有包名的,一类是路径中不含有包名的,含有包名的路径,因为和某个App有关,所以对这些文件夹的访问都是调用Context里边的方法,而不含有包名的路径,和某一个App无关,我们可以通过Environment中的方法来访问。如下图:

    大家看到,有包名的路径我们都是调用Context中的方法来获得,没有包名的路径,我们直接调用Environment中的方法获得,那么其中有两个方法需要传入一个String类型的参数,这个参数我们使用了Environment中的常量,参数的意思是我们要访问这个路径下的哪个文件夹,比如getExternalFilesDir方法,我们看看它的源码:

      1   /**
      2      *
      3      * @param type The type of files directory to return.  May be null for
      4      * the root of the files directory or one of
      5      * the following Environment constants for a subdirectory:
      6      * {@link android.os.Environment#DIRECTORY_MUSIC},
      7      * {@link android.os.Environment#DIRECTORY_PODCASTS},
      8      * {@link android.os.Environment#DIRECTORY_RINGTONES},
      9      * {@link android.os.Environment#DIRECTORY_ALARMS},
     10      * {@link android.os.Environment#DIRECTORY_NOTIFICATIONS},
     11      * {@link android.os.Environment#DIRECTORY_PICTURES}, or
     12      * {@link android.os.Environment#DIRECTORY_MOVIES}.
     13      *
     14      * @return The path of the directory holding application files
     15      * on external storage.  Returns null if external storage is not currently
     16      * mounted so it could not ensure the path exists; you will need to call
     17      * this method again when it is available.
     18      *
     19      * @see #getFilesDir
     20      * @see android.os.Environment#getExternalStoragePublicDirectory
     21      */
     22     @Nullable
     23     public abstract File getExternalFilesDir(@Nullable String type);
     24 它的注释非常多,我这里只列出其中一部分,我们看到,我们可以访问files文件夹下的Music文件夹、Movies文件夹等等好几种。
     25 
     26  
     27 
     28 说到这里,我想大家对内部存储、外部存储该有了一个清晰的认识了吧。我们在开发中,不建议往内部存储中写太多的数据,毕竟空间有限。外部存储在使用的时候最好能够将文件存放在私有目录下,这样有利于系统维护,也避免用户的反感。
     29 
     30 现在我们再来看看我们一开始提出的问题,当我们点击清除数据的时候清除的是哪里的数据呢?毫无疑问,当然是内部存储目录中相应的files和cache文件夹中的文件和外部存储中相应的files和cache文件夹中的文件,至于这些文件夹的路径我想你应该已经明白了。
     31 
     32 好了,最后再送给大家一个文件操作工具类:
     33 
     34  
     35 
     36 public class SDCardHelper {
     37 
     38     // 判断SD卡是否被挂载
     39     public static boolean isSDCardMounted() {
     40         // return Environment.getExternalStorageState().equals("mounted");
     41         return Environment.getExternalStorageState().equals(
     42                 Environment.MEDIA_MOUNTED);
     43     }
     44 
     45     // 获取SD卡的根目录
     46     public static String getSDCardBaseDir() {
     47         if (isSDCardMounted()) {
     48             return Environment.getExternalStorageDirectory().getAbsolutePath();
     49         }
     50         return null;
     51     }
     52 
     53     // 获取SD卡的完整空间大小,返回MB
     54     public static long getSDCardSize() {
     55         if (isSDCardMounted()) {
     56             StatFs fs = new StatFs(getSDCardBaseDir());
     57             long count = fs.getBlockCountLong();
     58             long size = fs.getBlockSizeLong();
     59             return count * size / 1024 / 1024;
     60         }
     61         return 0;
     62     }
     63 
     64     // 获取SD卡的剩余空间大小
     65     public static long getSDCardFreeSize() {
     66         if (isSDCardMounted()) {
     67             StatFs fs = new StatFs(getSDCardBaseDir());
     68             long count = fs.getFreeBlocksLong();
     69             long size = fs.getBlockSizeLong();
     70             return count * size / 1024 / 1024;
     71         }
     72         return 0;
     73     }
     74 
     75     // 获取SD卡的可用空间大小
     76     public static long getSDCardAvailableSize() {
     77         if (isSDCardMounted()) {
     78             StatFs fs = new StatFs(getSDCardBaseDir());
     79             long count = fs.getAvailableBlocksLong();
     80             long size = fs.getBlockSizeLong();
     81             return count * size / 1024 / 1024;
     82         }
     83         return 0;
     84     }
     85 
     86     // 往SD卡的公有目录下保存文件
     87     public static boolean saveFileToSDCardPublicDir(byte[] data, String type,
     88             String fileName) {
     89         BufferedOutputStream bos = null;
     90         if (isSDCardMounted()) {
     91             File file = Environment.getExternalStoragePublicDirectory(type);
     92             try {
     93                 bos = new BufferedOutputStream(new FileOutputStream(new File(
     94                         file, fileName)));
     95                 bos.write(data);
     96                 bos.flush();
     97                 return true;
     98             } catch (Exception e) {
     99                 e.printStackTrace();
    100             } finally {
    101                 try {
    102                     bos.close();
    103                 } catch (IOException e) {
    104                     // TODO Auto-generated catch block
    105                     e.printStackTrace();
    106                 }
    107             }
    108         }
    109         return false;
    110     }
    111 
    112     // 往SD卡的自定义目录下保存文件
    113     public static boolean saveFileToSDCardCustomDir(byte[] data, String dir,
    114             String fileName) {
    115         BufferedOutputStream bos = null;
    116         if (isSDCardMounted()) {
    117             File file = new File(getSDCardBaseDir() + File.separator + dir);
    118             if (!file.exists()) {
    119                 file.mkdirs();// 递归创建自定义目录
    120             }
    121             try {
    122                 bos = new BufferedOutputStream(new FileOutputStream(new File(
    123                         file, fileName)));
    124                 bos.write(data);
    125                 bos.flush();
    126                 return true;
    127             } catch (Exception e) {
    128                 e.printStackTrace();
    129             } finally {
    130                 try {
    131                     bos.close();
    132                 } catch (IOException e) {
    133                     // TODO Auto-generated catch block
    134                     e.printStackTrace();
    135                 }
    136             }
    137         }
    138         return false;
    139     }
    140 
    141     // 往SD卡的私有Files目录下保存文件
    142     public static boolean saveFileToSDCardPrivateFilesDir(byte[] data,
    143             String type, String fileName, Context context) {
    144         BufferedOutputStream bos = null;
    145         if (isSDCardMounted()) {
    146             File file = context.getExternalFilesDir(type);
    147             try {
    148                 bos = new BufferedOutputStream(new FileOutputStream(new File(
    149                         file, fileName)));
    150                 bos.write(data);
    151                 bos.flush();
    152                 return true;
    153             } catch (Exception e) {
    154                 e.printStackTrace();
    155             } finally {
    156                 try {
    157                     bos.close();
    158                 } catch (IOException e) {
    159                     // TODO Auto-generated catch block
    160                     e.printStackTrace();
    161                 }
    162             }
    163         }
    164         return false;
    165     }
    166 
    167     // 往SD卡的私有Cache目录下保存文件
    168     public static boolean saveFileToSDCardPrivateCacheDir(byte[] data,
    169             String fileName, Context context) {
    170         BufferedOutputStream bos = null;
    171         if (isSDCardMounted()) {
    172             File file = context.getExternalCacheDir();
    173             try {
    174                 bos = new BufferedOutputStream(new FileOutputStream(new File(
    175                         file, fileName)));
    176                 bos.write(data);
    177                 bos.flush();
    178                 return true;
    179             } catch (Exception e) {
    180                 e.printStackTrace();
    181             } finally {
    182                 try {
    183                     bos.close();
    184                 } catch (IOException e) {
    185                     // TODO Auto-generated catch block
    186                     e.printStackTrace();
    187                 }
    188             }
    189         }
    190         return false;
    191     }
    192 
    193     // 保存bitmap图片到SDCard的私有Cache目录
    194     public static boolean saveBitmapToSDCardPrivateCacheDir(Bitmap bitmap,
    195             String fileName, Context context) {
    196         if (isSDCardMounted()) {
    197             BufferedOutputStream bos = null;
    198             // 获取私有的Cache缓存目录
    199             File file = context.getExternalCacheDir();
    200 
    201             try {
    202                 bos = new BufferedOutputStream(new FileOutputStream(new File(
    203                         file, fileName)));
    204                 if (fileName != null
    205                         && (fileName.contains(".png") || fileName
    206                                 .contains(".PNG"))) {
    207                     bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
    208                 } else {
    209                     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
    210                 }
    211                 bos.flush();
    212             } catch (Exception e) {
    213                 e.printStackTrace();
    214             } finally {
    215                 if (bos != null) {
    216                     try {
    217                         bos.close();
    218                     } catch (IOException e) {
    219                         e.printStackTrace();
    220                     }
    221                 }
    222             }
    223             return true;
    224         } else {
    225             return false;
    226         }
    227     }
    228 
    229     // 从SD卡获取文件
    230     public static byte[] loadFileFromSDCard(String fileDir) {
    231         BufferedInputStream bis = null;
    232         ByteArrayOutputStream baos = new ByteArrayOutputStream();
    233 
    234         try {
    235             bis = new BufferedInputStream(
    236                     new FileInputStream(new File(fileDir)));
    237             byte[] buffer = new byte[8 * 1024];
    238             int c = 0;
    239             while ((c = bis.read(buffer)) != -1) {
    240                 baos.write(buffer, 0, c);
    241                 baos.flush();
    242             }
    243             return baos.toByteArray();
    244         } catch (Exception e) {
    245             e.printStackTrace();
    246         } finally {
    247             try {
    248                 baos.close();
    249                 bis.close();
    250             } catch (IOException e) {
    251                 e.printStackTrace();
    252             }
    253         }
    254         return null;
    255     }
    256 
    257     // 从SDCard中寻找指定目录下的文件,返回Bitmap
    258     public Bitmap loadBitmapFromSDCard(String filePath) {
    259         byte[] data = loadFileFromSDCard(filePath);
    260         if (data != null) {
    261             Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
    262             if (bm != null) {
    263                 return bm;
    264             }
    265         }
    266         return null;
    267     }
    268 
    269     // 获取SD卡公有目录的路径
    270     public static String getSDCardPublicDir(String type) {
    271         return Environment.getExternalStoragePublicDirectory(type).toString();
    272     }
    273 
    274     // 获取SD卡私有Cache目录的路径
    275     public static String getSDCardPrivateCacheDir(Context context) {
    276         return context.getExternalCacheDir().getAbsolutePath();
    277     }
    278 
    279     // 获取SD卡私有Files目录的路径
    280     public static String getSDCardPrivateFilesDir(Context context, String type) {
    281         return context.getExternalFilesDir(type).getAbsolutePath();
    282     }
    283 
    284     public static boolean isFileExist(String filePath) {
    285         File file = new File(filePath);
    286         return file.isFile();
    287     }
    288 
    289     // 从sdcard中删除文件
    290     public static boolean removeFileFromSDCard(String filePath) {
    291         File file = new File(filePath);
    292         if (file.exists()) {
    293             try {
    294                 file.delete();
    295                 return true;
    296             } catch (Exception e) {
    297                 return false;
    298             }
    299         } else {
    300             return false;
    301         }
    302     }
    303 }

     本文相关笔记和源码下载http://download.csdn.net/detail/u012702547/9348985

  • 相关阅读:
    计算十位数以内的数的反数
    用Python做一个简单的小游戏
    Python的发展历史及其前景
    监控相关总结
    前端css学习_Day15
    常用命令总结
    mysql常用命令总结
    Python之Paramiko、前端之html学习_Day14
    Python操作redis、memcache和ORM框架_Day13
    Python连接msyql、redis学习_Day12
  • 原文地址:https://www.cnblogs.com/tsingke/p/9102191.html
Copyright © 2020-2023  润新知