Unified Cache Management Tool-android

Source: Internet
Author: User

Unified Cache Management Tool-android

Import android. content. context; import android. OS. environment; import android. support. annotation. nullable; import com. lidroid. xutils. db. annotation. notNull; import junit. framework. assert; import. r; import. utils. *; import java. io. file; import java. util. arrayList; import java. util. hashMap; import java. util. list;/*** Created by xiaoyee on 7/12/15. * Cache Management tool *

* If you want to add a cache path, add the corresponding type in {@ link. constants. IYDCache. DirType *

*/Public class IYDCache {private static final String TAG = IYDCache; public static final String CACHE_ROOT = root_cache; public static final String CACHE_VIDEO = video_cache; public static final String CACHE_IMAGE = image_cache; public static final String CACHE_VIDEO_MATERIAL = material_cache; // The private static String mCacheDir; private static String mPicCachePath; private static String ROOT_DIR;/*** stores all cache file paths *

* *

  • Key -- {@ link DirType # dirName () DirType dirName method return value}
  • *
    • Value -- full path, such as/storage/emulated/0/Android/root_cache/video_cache
    • * *

       

      */Private static HashMap MCacheDirBox = new HashMap <> ();/*** type of the first failure due to parent directory initialization */private static List MInitFailedDirType = new ArrayList <> ();/*** optional */private static final String IYD = iyd;/*** whether Initialization is successful */private static boolean mIsInited = false; /* file type */public enum FileType {PNG(.png), JPG(.jpg), MP4(.mp4);/*** suffix name */final String mSuffix; FileType (String suffix) {this. mSuffix = suffix;}/*** get the suffix ** @ return indicates the suffix of the suffix, for example, '.mp4 '*/public String suffix () {re Turn this. mSuffix ;}}/*** obtain this complete path based on the cache type, cache file type, and its url, for example,/storage/emulated/0/Android/root_cache/video_cache/iyd1736054267.mp4 ** @ param type cache type. Here, we use enumeration to ensure that the cache path you want to use has been added. If you do not remember to add the * @ param url to the cache destination url, the corresponding link to the slice * @ param fileType file type, for example, mp4, png, etc. If you want to expand, please go to {@ link. constants. IYDCache. add * @ return results in The FileType}, such as/storage/emulated/0/Android/root_cache/video_cache/iyd1736054267.mp4 */public static String getFileNameWithPath (DirType type, String url, fileType fileType) {return getIYDCacheDirThisType (type) + File. separator + generateNameFromUrl (url, fileType);}/*** generate a file name based on the url. If the url is the same, the return value is the same *

      * // NOTE: This file name contains a suffix *

      *

      * It is actually the combination of iyd + url hash value + suffix *

      ** @ Param url the target url * @ param fileType file type * @ return result form, for example, iyd1736054267.mp4 */public static String generateNameFromUrl (String url, FileType fileType) {if (StringUtils. isBlank (url) {return StringUtils. empty ();} return IYD + url. hashCode () + fileType. suffix ();}/*** Based on the hash value, no extension name for the generated file name ** @ param hashcode target hash value * @ return result, for example, iyd1736054267 */public static String generateNameFromHashcode (int hashcode) {return IYD + hashcode ;} /*** generate a file name based on the object; no suffix *

      * The purpose here is to ensure that the same object returns the same file name, but it depends on the equal method and hashCode method of the object *

      ** @ Return result, such as iyd1736054267 */public static String generateNameFromObj (Object obj) {return IYD + obj. hashCode ();}/*** get the cache folder of the specified cache type *

      * Note: The return value can be blank *

      ** @ Param type: cache type {@ link. constants. IYDCache. dirType} * @ return, such as/storage/emulated/0/Android/root_cache/video_cache or "/storage/emulated/0/Android/root_cache" */@ Nullable public static String getIYDCacheDirThisType (DirType type) {if (! MIsInited) {throw new IllegalArgumentException (ResourceUtils. getString (R. string. not_init) + make sure that the initCacheDir method of this class is called in the application);} String key = type. dirName (); if (mCacheDirBox. containsKey (key) {return mCacheDirBox. get (key);} else {LogCus. e (TAG, the corresponding directory + key is not found); return StringUtils. empty () ;}}/*** clears all content in the specified cache folder * @ param dirType specifies that the cache folder type corresponds to {@ link. constants. IYDCache. dirType }*/ Public static void implements achethisdir (final DirType dirType) {new Thread (new Runnable () {@ Override public void run () {FileUtils. clearDir (getIYDCacheDirThisType (dirType ));}}). start ();}/*** Initialize all cache folders. You should call */public static void initCacheDir (Context context) {if (! SDCardUtil. isSDCardExist () {ToastUtils. show (context, ResourceUtils. getString (R. string. check_memory_is_ OK); return;} File androidDir = Environment. getExternalStoragePublicDirectory (Android); ROOT_DIR = androidDir. getAbsolutePath (); mIsInited = true; // Initialize all cache folders DirType [] allDirType = DirType. values (); for (DirType dirType: allDirType) {initDirWithParentDirType (dirType);} // for (DirT) Ype dirType: mInitFailedDirType) {initDirWithParentDirType (dirType) ;}} private static void partition (DirType childDir) {String parentDirPath; // if the parent directory is not initialized, first initialize the subdirectory... // Obtain the parent directory path if (childDir = DirType. ROOT) {// if it is the ROOT directory, define if (StringUtils. isBlank (ROOT_DIR) {throw new IllegalArgumentException (initialize the root directory first, that is, call ROOT_DIR = androidDir first. getAbsolutePath ();} parentDirPath = ROOT_DIR;} else {// otherwise, set it directly. The complete path of the parent directory folder should be obtained through the directory name corresponding to the parent directory. parentDirPath = mCacheDirBox. get (childDir. parentDirType (). dirName ();} LogCus. d (parent path> + parentDirPath); if (StringUtils. isBlank (pa RentDirPath) |! ParentDirPath. contains (ROOT_DIR) {mInitFailedDirType. add (childDir); return;} String dirPath = spliceSeparator (parentDirPath, childDir. dirName (); if (! FileUtils. isFolderExistOrCreateSuccess (dirPath) {LogCus. d (failed to initialize the folder + dirPath); return;} mCacheDirBox. put (childDir. dirName (), dirPath);} private static String spliceSeparator (String... dir) {StringBuilder result = new StringBuilder (); for (String s: dir) {result. append (s); result. append (File. separator);} return result. toString ();} public static String getCacheDir () {return mCacheDir;} public static void setCacheDir (String mCacheDir) {IYDCache. mCacheDir = mCacheDir;}/*** cache folder type, // NOTE: ensure the added type. Its dir and parentDir paths are defined in this class *

      * Note the order in this enumeration type. The parent directory must be written before the subdirectory *

      */Public enum DirType {/*** cache ROOT directory iyd_cache */ROOT (CACHE_ROOT, ROOT_DIR),/*** video cache directory video_cache; its parent directory is CACHE_ROOT */VIDEO (CACHE_VIDEO, CACHE_ROOT),/*** IMAGE cache directory is image_cache, and its parent directory is CACHE_ROOT */IMAGE (CACHE_IMAGE, CACHE_ROOT ), /*** MATERIAL cache directory material_cache; its parent directory is CACHE_ROOT */MATERIAL (CACHE_VIDEO_MATERIAL, CACHE_ROOT); private String mDir; private String mParentDir; public String getParentDir () {return mParentDir;}/*** @ param dir current directory name * @ param parentDir parent directory name */DirType (String dir, String parentDir) {this. mDir = dir; this. mParentDir = parentDir;} public void setParentDir (String parentDir) {this. mParentDir = parentDir;}/*** get the name of the cache folder, such as video_cache ** @ return returned result, such as video_cache */public String dirName () {return mDir ;} /*** obtain the DirType of the parent directory. When calling this method, make sure it is not ROOT */public DirType parentDirType () {DirType [] dirTypes = DirType. values (); for (DirType dirType: dirTypes) {// The parent directory of this item, corresponding to the current directory of an item if (mParentDir. equals (dirType. dirName () {return dirType;} throw new IllegalArgumentException (the corresponding parent folder is not found >>>+ mParentDir +; 1. Make sure that the mParentDir has been added. 2. Make sure that the type of the method called is not ROOT );}}}

      How to clear a folder

      /*** Removes subdirectories and their contents */static void purgeDirectory (File dir) {for (File file File: dir. listFiles () {if (file. isDirectory () purgeDirectory (file); file. delete () ;}}/*** clear the content in the folder, including the subdirectory * @ param path */public static void clearDir (String path) {// LogCus. d (delete all contents in the + path + directory); if (StringUtils. isBlank (path) {return;} File file = new File (path); purgeDirectory (file );}

       

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.