Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 緩存統一管理工具類設計:目錄初始化與檔案命名策略

編輯:關於 Android 程式設計

專案裡圖片、影片、素材各自散落在不同路徑,久了就成一團亂。這篇示範如何把緩存路徑集中封裝成一個工具類,用列舉管理目錄層級、用 hash 生成檔名,並提供清空指定目錄的能力。

設計要點

  • 所有緩存路徑集中在一個 HashMap 中,key 是目錄名稱,value 是完整路徑。
  • 用列舉 DirType 描述目錄與其父目錄的關係,確保新增類型時父子順序不會出錯。
  • 檔名由「前綴 + url.hashCode() + 副檔名」組成,保證同一個 url 永遠對應同一個檔名。
  • 初始化失敗的目錄會被記下來再重試一次,處理父目錄尚未就緒的先後問題。
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";

    private static String ROOT_DIR;
    /** 存放所有緩存目錄路徑:key 為 DirType.dirName(),value 為完整路徑 */
    private static final HashMap<String, String> mCacheDirBox = new HashMap<>();
    /** 第一次因父目錄未初始化而失敗的類型 */
    private static final List<DirType> mInitFailedDirType = new ArrayList<>();
    /** 檔名前綴,例如 iyd1736054267.mp4 */
    private static final String IYD = "iyd";
    private static boolean mIsInited = false;

    /** 支援的檔案類型 */
    public enum FileType {
        PNG(".png"), JPG(".jpg"), MP4(".mp4");
        final String mSuffix;
        FileType(String suffix) { this.mSuffix = suffix; }
        public String suffix() { return mSuffix; }
    }

    /**
     * 取得某緩存類型下、對應 url 的完整檔案路徑
     * @return 形如 /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);
    }

    /** 由 url 生成檔名,url 相同則結果必定相同(含副檔名) */
    public static String generateNameFromUrl(String url, FileType fileType) {
        if (StringUtils.isBlank(url)) return StringUtils.empty();
        return IYD + url.hashCode() + fileType.suffix();
    }

    /** 由物件生成檔名(無副檔名),依賴 equals / hashCode 實作 */
    public static String generateNameFromObj(Object obj) {
        return IYD + obj.hashCode();
    }

    /** 取得指定類型的緩存目錄,可能為空字串 */
    @Nullable
    public static String getIYDCacheDirThisType(DirType type) {
        if (!mIsInited) {
            throw new IllegalArgumentException(
                ResourceUtils.getString(R.string.not_init)
                + " 請確保在 Application 中呼叫了 initCacheDir 方法");
        }
        String key = type.dirName();
        if (mCacheDirBox.containsKey(key)) {
            return mCacheDirBox.get(key);
        }
        LogCus.e(TAG, "沒找到與此對應的目錄 " + key);
        return StringUtils.empty();
    }

    /** 清空指定緩存目錄中的所有內容(背景執行緒) */
    public static void clearCacheThisDir(final DirType dirType) {
        new Thread(new Runnable() {
            @Override public void run() {
                FileUtils.clearDir(getIYDCacheDirThisType(dirType));
            }
        }).start();
    }

    /** 初始化所有緩存目錄,應在 Application.onCreate 中呼叫 */
    public static void initCacheDir(Context context) {
        if (!SDCardUtil.isSDCardExist()) {
            ToastUtils.show(context, ResourceUtils.getString(R.string.check_memory_is_ok));
            return;
        }
        ROOT_DIR = Environment.getExternalStoragePublicDirectory("Android").getAbsolutePath();
        mIsInited = true;

        for (DirType dirType : DirType.values()) {
            initDirWithParentDirType(dirType);
        }
        // 再重試一次先前失敗的
        for (DirType dirType : mInitFailedDirType) {
            initDirWithParentDirType(dirType);
        }
    }

    private static void initDirWithParentDirType(DirType childDir) {
        String parentDirPath;
        if (childDir == DirType.ROOT) {
            if (StringUtils.isBlank(ROOT_DIR)) {
                throw new IllegalArgumentException("請先初始化根目錄");
            }
            parentDirPath = ROOT_DIR;
        } else {
            parentDirPath = mCacheDirBox.get(childDir.parentDirType().dirName());
        }
        if (StringUtils.isBlank(parentDirPath) || !parentDirPath.contains(ROOT_DIR)) {
            mInitFailedDirType.add(childDir);
            return;
        }
        String dirPath = spliceSeparator(parentDirPath, childDir.dirName());
        if (!FileUtils.isFolderExistOrCreateSuccess(dirPath)) {
            LogCus.d("初始化文件夾失敗 " + dirPath);
            return;
        }
        mCacheDirBox.put(childDir.dirName(), dirPath);
    }

    private static String spliceSeparator(String... dir) {
        StringBuilder result = new StringBuilder();
        for (String s : dir) {
            result.append(s).append(File.separator);
        }
        return result.toString();
    }

    /** 緩存目錄類型;注意:父目錄一定要寫在子目錄之前 */
    public enum DirType {
        ROOT(CACHE_ROOT, ROOT_DIR),
        VIDEO(CACHE_VIDEO, CACHE_ROOT),
        IMAGE(CACHE_IMAGE, CACHE_ROOT),
        MATERIAL(CACHE_VIDEO_MATERIAL, CACHE_ROOT);

        private final String mDir;
        private final String mParentDir;

        DirType(String dir, String parentDir) {
            this.mDir = dir;
            this.mParentDir = parentDir;
        }

        public String dirName() { return mDir; }

        /** 取得父目錄的 DirType;呼叫時務必確認自己不是 ROOT */
        public DirType parentDirType() {
            for (DirType dirType : DirType.values()) {
                if (mParentDir.equals(dirType.dirName())) return dirType;
            }
            throw new IllegalArgumentException(
                "沒找到對應的父文件夾 " + mParentDir
                + ";1、請確保已經添加並定義了 mParentDir;2、請確認呼叫者不是 ROOT");
        }
    }
}

清空目錄的實作

刪除目錄內容時用遞迴最乾脆,子目錄先清再刪本體:

/** 遞迴移除子目錄及其內容 */
static void purgeDirectory(File dir) {
    File[] children = dir.listFiles();
    if (children == null) return;
    for (File file : children) {
        if (file.isDirectory()) purgeDirectory(file);
        file.delete();
    }
}

/** 清空目錄內容(含子目錄) */
public static void clearDir(String path) {
    if (StringUtils.isBlank(path)) return;
    purgeDirectory(new File(path));
}

使用提醒

這套設計有兩個容易踩到的點。第一,DirType 的宣告順序有意義——父目錄必須排在子目錄之前,否則首次初始化時子目錄會找不到父路徑(程式碼用重試清單做了補救,但別依賴它)。第二,initCacheDir() 一定要在 Application 的 onCreate 裡提早呼叫,之後各處才能安全地取得路徑;否則 getIYDCacheDirThisType() 會直接拋例外提醒你。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved