Internal and external storage in Android

Keywords: Android network xml Database

Learn from time to time, not to mention!

Today I'm going to summarize the internal and external storage of APP in Android

In Android development, we often encounter memory, external storage, internal storage.We have data cleanup and cache cleanup in our Android phone settings, and I don't think part of it knows what storage to clean up.

Memory: As the name implies, it is the space in which the app on your phone runs

1. Internal Storage

The important folder is the data folder, which contains package names. When you open these package names, you will see some of these files:

1.data/data/package name/shared_prefs
2.data/data/package name/databases
3.data/data/package name/files

4.data/data/package name/cache

If you've opened a data file, you know what these folders are for. When we use sharedPreferenced, we store the data persistently locally, in fact, there are xml files in this file. The database files inside our App are stored in the databases folder. Our normal data is stored in the files, and the cache files are stored in the CAIn the Che folder, the files stored here are called internal storage.

2. External Storage

External storage is usually the storage folder that we see above, and of course it may also be the mnt folder, which may be different for different manufacturers.

Generally speaking, there is an sdcard folder in the storage folder. The files in this folder can be divided into two categories: public directory and private directory. There are nine categories of public directory, such as DCIM, DOWNLOAD and other folders created for us by the system. The private directory is the Android folder. Once opened, there is one inside the folder.Data folder, open this data folder, there are many folders made up of package names inside, when you delete the application, the private directory of the external storage of the application will also be deleted.

Speaking of this, I think you can tell what internal storage is and what external storage is.Okay, after that we'll see how to operate internal and external storage.

If your api version is less than 8, you can't use getExternal FilesDir (), but use Environment.getExternal Storage Directory () to get the root path and then try to manipulate the files under / Android/data/// yourself.
That is, versions below api 8 do not specifically provide api support for private and public file operations when manipulating files.You can only get the root directory first, and then try your own way.

3. Operational memory space

An operation tool class:

public class SDCardHelper {

     // Determine if SD card is mounted
     public static boolean isSDCardMounted() {
         // return Environment.getExternalStorageState().equals("mounted");
         return Environment.getExternalStorageState().equals(
         Environment.MEDIA_MOUNTED);
    }

    // Get the root directory of the SD card
    public static String getSDCardBaseDir() {
         if (isSDCardMounted()) {
               return Environment.getExternalStorageDirectory().getAbsolutePath();
         }
         return null;
    }

    // Get the full space size of the SD card, return MB
    public static long getSDCardSize() {
         if (isSDCardMounted()) {
              StatFs fs = new StatFs(getSDCardBaseDir());
              long count = fs.getBlockCountLong();
              long size = fs.getBlockSizeLong();
              return count * size / 1024 / 1024;
         }
         return 0;
    }

    // Get the remaining space size of the SD card
    public static long getSDCardFreeSize() {
         if (isSDCardMounted()) {
               StatFs fs = new StatFs(getSDCardBaseDir());
               long count = fs.getFreeBlocksLong();
               long size = fs.getBlockSizeLong();
               return count * size / 1024 / 1024;
         }
         return 0;
    }

    // Get the free space size of the SD card
    public static long getSDCardAvailableSize() {
         if (isSDCardMounted()) {
               StatFs fs = new StatFs(getSDCardBaseDir());
               long count = fs.getAvailableBlocksLong();
               long size = fs.getBlockSizeLong();
               return count * size / 1024 / 1024;
         }
         return 0;
    }

    // Save files in the public directory of the SD card
    public static boolean saveFileToSDCardPublicDir(byte[] data, String type, String fileName) {
         BufferedOutputStream bos = null;
         if (isSDCardMounted()) {
               File file = Environment.getExternalStoragePublicDirectory(type);
               try {
                    bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
                    bos.write(data);
                    bos.flush();
                    return true;
               } catch (Exception e) {
                    e.printStackTrace();
               } finally {
                    try {
                          bos.close();
                    } catch (IOException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                    }
               }
          }
          return false;
     }

     // Save files to SD card's custom directory
     public static boolean saveFileToSDCardCustomDir(byte[] data, String dir, String fileName) {
          BufferedOutputStream bos = null;
          if (isSDCardMounted()) {
                File file = new File(getSDCardBaseDir() + File.separator + dir);
                if (!file.exists()) {
                      file.mkdirs();// Recursively create custom directories
                }
                try {
                      bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
                      bos.write(data);
                      bos.flush();
                      return true;
                } catch (Exception e) {
                      e.printStackTrace();
                } finally {
                      try {
                            bos.close();
                      } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                      }
                }
           }
           return false;
     }

     // Save files to SD card's private Files directory
     public static boolean saveFileToSDCardPrivateFilesDir(byte[] data, String type, String fileName, Context context) {
         BufferedOutputStream bos = null;
         if (isSDCardMounted()) {
               File file = context.getExternalFilesDir(type);
               try {
                      bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
                      bos.write(data);
                      bos.flush();
                      return true;
               } catch (Exception e) {
                      e.printStackTrace();
               } finally {
                      try {
                            bos.close();
                      } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                      }
               }
          }
          return false;
     }

     // Save files to SD card's private Cache directory
     public static boolean saveFileToSDCardPrivateCacheDir(byte[] data, String fileName, Context context) {
          BufferedOutputStream bos = null;
          if (isSDCardMounted()) {
                File file = context.getExternalCacheDir();
                try {
                      bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
                      bos.write(data);
                      bos.flush();
                      return true;
                } catch (Exception e) {
                      e.printStackTrace();
                } finally {
                      try {
                            bos.close();
                      } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                      }
               }
          }
          return false;
     }

     // Private Cache directory to save bitmap pictures to SDCard
     public static boolean saveBitmapToSDCardPrivateCacheDir(Bitmap bitmap, String fileName, Context context) {
          if (isSDCardMounted()) {
                BufferedOutputStream bos = null;
                // Get the private Cache cache directory
                File file = context.getExternalCacheDir();

                try {
                       bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
                       if (fileName != null && (fileName.contains(".png") || fileName.contains(".PNG"))) {
                              bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
                       } else {
                              bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                       }
                       bos.flush();
                } catch (Exception e) {
                       e.printStackTrace();
                } finally {
                       if (bos != null) {
                            try {
                                 bos.close();
                            } catch (IOException e) {
                                 e.printStackTrace();
                            }
                       }
                 }
                 return true;
          } else {
                return false;
          }
     }

     // Get files from SD card
     public static byte[] loadFileFromSDCard(String fileDir) {
          BufferedInputStream bis = null;
          ByteArrayOutputStream baos = new ByteArrayOutputStream();

          try {
                bis = new BufferedInputStream(new FileInputStream(new File(fileDir)));
                byte[] buffer = new byte[8 * 1024];
                int c = 0;
                while ((c = bis.read(buffer)) != -1) {
                     baos.write(buffer, 0, c);
                     baos.flush();
                }
                return baos.toByteArray();
          } catch (Exception e) {
                e.printStackTrace();
          } finally {
                try {
                     baos.close();
                     bis.close();
                } catch (IOException e) {
                     e.printStackTrace();
                }
          }
          return null;
     }

     // Find the file in the specified directory from the SDCard and return to Bitmap
     public Bitmap loadBitmapFromSDCard(String filePath) {
          byte[] data = loadFileFromSDCard(filePath);
          if (data != null) {
               Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
               if (bm != null) {
                     return bm;
               }
          }
          return null;
     }

     // Path to get SD card public directory
     public static String getSDCardPublicDir(String type) {
          return Environment.getExternalStoragePublicDirectory(type).toString();
     }

     // Path to get SD card private Cache directory
     public static String getSDCardPrivateCacheDir(Context context) {
          return context.getExternalCacheDir().getAbsolutePath();
     }

     // Path to get SD card private Files directory
     public static String getSDCardPrivateFilesDir(Context context, String type) {
          return context.getExternalFilesDir(type).getAbsolutePath();
     }

     public static boolean isFileExist(String filePath) {
          File file = new File(filePath);
          return file.isFile();
     }

     // Delete files from sdcard
     public static boolean removeFileFromSDCard(String filePath) {
          File file = new File(filePath);
          if (file.exists()) {
               try {
                     file.delete();
                     return true;
               } catch (Exception e) {
                     return false;
               }
          } else {
               return false;
          }
     }
}

Summary:

Cleaning up data mainly clears user configurations, such as SharedPreferences, databases, etc. These data are user configuration information saved during the running of the program. After clearing the data, the next time you enter the program, it will be the same as the first time you enter the program.

The cache is the temporary storage space for the program to run. It can store temporary pictures downloaded from the network. Clearing the cache from the user's point of view does not have a big impact on users. However, when users use the APP again after clearing the cache, all data needs to be retrieved from the network because the local cache has been cleared.In order to clear the application-related cache properly when clearing the cache, store the cache file in the getCacheDir() or getExternal CacheDir () path.

Posted by Cantaloupe on Sat, 08 Jun 2019 10:36:45 -0700