基于LRU算法的本地文件缓存

需求:

  • 管理下载文件、按照LRU算法删除不用的文件
  • 如果磁盘空间低于预期,预警提示
  • 如果下载文件过大,预警提示

缓存淘汰算法--LRU算法

LRU(Least recently used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”。

实现

说明
  • FileCacheOptions类 用于配置缓存的信息
    • cacheRootPath 缓存路径
    • maxFileCount 最大文件数
    • maxCacheSize 最大缓存空间
    • isUseFileCache 是否使用缓存等
  • LRUFileCache 采用Lru算法思路来管理下载文件
核心代码

_ 全部代码参考:https://github.com/CJstar/Android-ImageFileCache _

  • FileCacheOptions
public final class FileCacheOptions {
    /**
     * the file cache root path
     */
    private String cacheRootPath;
    /**
     * file cache count
     */
    private int maxFileCount;
    /**
     * file cache max size: byte
     */
    private long maxCacheSize;
    /**
     * if it is false, will not cache files
     */
    private boolean isUseFileCache = true;

    /**
     *  free sd space needed cache
     */
    private long minFreeSDCardSpace;

    public String getCacheRootPath() {
        return cacheRootPath;
    }

    public void setCacheRootPath(String cacheRootPath) {
        this.cacheRootPath = cacheRootPath;
    }

    public int getMaxFileCount() {
        return maxFileCount;
    }

    public void setMaxFileCount(int maxFileCount) {
        this.maxFileCount = maxFileCount;
    }

    /**
     * cache size in bytes
     *
     * @return
     */
    public long getMaxCacheSize() {
        return maxCacheSize;
    }

    public void setMaxCacheSize(long maxCacheSize) {
        this.maxCacheSize = maxCacheSize;
    }

    public boolean isUseFileCache() {
        return isUseFileCache;
    }

    public void setIsUseFileCache(boolean isUseFileCache) {
        this.isUseFileCache = isUseFileCache;
    }

    private FileCacheOptions(Builder builder) {
        setCacheRootPath(builder.getCacheRootPath());
        setIsUseFileCache(builder.isUseFileCache());
        setMaxCacheSize(builder.getMaxCacheSize());
        setMaxFileCount(builder.getMaxFileCount());
    }

    /**
     * This is the options set builder, we can create the options by this method
     */
    public static class Builder {
        private String cacheRootPath;
        private int maxFileCount;
        private long maxCacheSize;
        private boolean isUseFileCache;

        public Builder() {
        }

        public String getCacheRootPath() {
            return cacheRootPath;
        }

        public Builder setCacheRootPath(String cacheRootPath) {
            this.cacheRootPath = cacheRootPath;
            return this;
        }

        public int getMaxFileCount() {
            return maxFileCount;
        }

        public Builder setMaxFileCount(int maxFileCount) {
            this.maxFileCount = maxFileCount;
            return this;
        }

        public long getMaxCacheSize() {
            return maxCacheSize;
        }

        public Builder setMaxCacheSize(long maxCacheSize) {
            this.maxCacheSize = maxCacheSize;
            return this;
        }

        public boolean isUseFileCache() {
            return isUseFileCache;
        }

        public Builder setIsUseFileCache(boolean isUseFileCache) {
            this.isUseFileCache = isUseFileCache;
            return this;
        }

        public FileCacheOptions builder() {
            return new FileCacheOptions(this);
        }
    }
}

  • LRUFileCache
public class LRUFileCache implements FileCache {

    /**
     * file cache  config
     */
    private FileCacheOptions options;
    /**
     * cache file suffix
     */
    private static final String WHOLESALE_CONV = "";
    /**
     * mini free space on SDCard  100M
     */
    private static final long FREE_SD_SPACE_NEEDED_TO_CACHE = 100 * 1024 * 1024L;

    private static LRUFileCache mLRUFileCache;

    public static LRUFileCache getInstance() {
        if (mLRUFileCache == null) {
            synchronized (LRUFileCache.class) {
                if (mLRUFileCache == null) {
                    mLRUFileCache = new LRUFileCache();
                }
            }
        }

        return mLRUFileCache;
    }

    /**
     * 缓存文件的配置
     */
    public void setFileLoadOptions(FileCacheOptions options) {
        this.options = options;
    }

    /**
     * use default options
     */
    private LRUFileCache() {
        this.options = new FileCacheOptions.Builder()
                .setCacheRootPath("FileCache")
                .setIsUseFileCache(true)
                .setMaxCacheSize(100 * 1024 * 1024L)//100MB
                .setMaxFileCount(100)
                .builder();
    }


    @Override
    public void addDiskFile(String key, InputStream inputStream) {
        if (TextUtils.isEmpty(key) || inputStream == null) {
            return;
        }

        String filename = convertUrlToFileName(key);
        String dir = options.getCacheRootPath();
        File dirFile = new File(dir);
        if (!dirFile.exists())
            dirFile.mkdirs();
        File file = new File(dir + "/" + filename);
        OutputStream outStream;
        try {
            if (file.exists()) {
                file.delete();
            }

            file.createNewFile();
            outStream = new FileOutputStream(file);
            while (inputStream.available() != 0) {
                outStream.write(inputStream.read());
            }
            outStream.flush();
            outStream.close();
            inputStream.close();
        } catch (Throwable e) {
            Log.w("LRUFileCache", e.getMessage());
        }

        // free the space at every time to add a new file
        freeSpaceIfNeeded();
    }

    @Override
    public File getDiskFile(String key) {
        File file = new File(getFilePathByKey(key));

        if (file != null && file.exists()) {
            updateFileTime(file);

        } else {
            file = null;
        }
        return file;
    }

    @Override
    public boolean isExist(String key) {
        if (URLUtil.isNetworkUrl(key)) {
            return new File(options.getCacheRootPath() + "/" + convertUrlToFileName(key)).exists();

        } else if (URLUtil.isFileUrl(key)) {
            return new File(key).exists();

        } else {
            return false;
        }
    }

    @Override
    public void removeDiskFile(String key) {
        File file = getDiskFile(key);
        if (file != null && file.exists()) {
            file.delete();
        }
    }

    @Override
    public void removeAllDiskFiles() {
        new File(options.getCacheRootPath()).delete();
    }


    /**
     * This method will free the files which had not been used at a long time
     */
    public void freeSpaceIfNeeded() {
        File dir = new File(options.getCacheRootPath());
        File[] files = dir.listFiles();
        if (files == null) {
            return;
        }

        long dirSize = 0;
        for (int i = 0; i < files.length; i++) {
            if (files[i].getName().contains(WHOLESALE_CONV)) {
                dirSize += files[i].length();
            }
        }
        // if the dir size larger than max size or the free space on SDCard is less than 100MB
        //free 40% space for system
        if (dirSize > options.getMaxCacheSize()
                || FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
            // delete 40% files by LRU
            int removeFactor = (int) ((0.4 * files.length) + 1);
            // sort the files by modify time
            Arrays.sort(files, new FileLastModifSort());
            // delete files
            for (int i = 0; i < removeFactor; i++) {
                if (files[i].getName().contains(WHOLESALE_CONV)) {
                    files[i].delete();
                }
            }
        }

        //if file count is larger than max count, delete the last
        if (files.length > options.getMaxFileCount()) {
            Arrays.sort(files, new FileLastModifSort());
            // delete files
            for (int i = 0; i < files.length - options.getMaxFileCount(); i++) {
                if (files[i].getName().contains(WHOLESALE_CONV)) {
                    files[i].delete();
                }
            }
        }

    }

    /**
     * Modify the file time
     *
     * @param file the file which need to update time
     */
    public void updateFileTime(File file) {
        if (file != null && file.exists()) {
            long newModifiedTime = System.currentTimeMillis();
            file.setLastModified(newModifiedTime);
        }
    }

    /**
     * get the free space on SDCard
     *
     * @return free size in B
     */

    private long freeSpaceOnSd() {
        return SDCardUtil.getfreeSpace();
    }

    /**
     * Get the file name by file url
     *
     * @param url
     * @return file name
     */
    private String convertUrlToFileName(String url) {
        String[] strs = url.split("/");
        return strs[strs.length - 1] + WHOLESALE_CONV;
    }

    /**
     * Get the file name by key
     *
     * @param key
     * @return file name
     */
    public String getFilePathByKey(String key) {
        if (URLUtil.isFileUrl(key)) {
            return key;

        } else if (URLUtil.isNetworkUrl(key)) {
            return options.getCacheRootPath() + "/" + convertUrlToFileName(key);

        } else {
            return null;
        }
    }

    /**
     * The comparator for the file modify, sort the files by modify time.
     */
    private class FileLastModifSort implements Comparator<File> {
        public int compare(File arg0, File arg1) {
            if (arg0.lastModified() > arg1.lastModified()) {
                return 1;
            } else if (arg0.lastModified() == arg1.lastModified()) {
                return 0;
            } else {
                return -1;
            }
        }
    }
}

  • SDCardUtil 工具类
public class SDCardUtil {
    public static final long SIZE_KB = 1024L;
    public static final long SIZE_MB = 1024L * 1024L;
    public static final long SIZE_GB = 1024L * 1024L * 1024L;

    public interface AlarmListener {
        void onAlarm();
    }
    
    //设置超出最大值
    public static void setAlarmSize(long currentSize, long maxSize, SDSizeAlarmUtil.AlarmListener listener) {
        if (currentSize > maxSize) {
            if (listener != null) {
                listener.onAlarm();
            }
        }
    }

    //设置超出最小磁盘值预警
    public static void setSDAlarm(long minSize, SDSizeAlarmUtil.AlarmListener listener) {
        long freeSize = getFreeSpace();
        if (freeSize < minSize) {
            if (listener != null) {
                listener.onAlarm();
            }
        }
    }


    public static boolean sDCardIsCanable() {
        String sDStateString = Environment.getExternalStorageState();
        if (sDStateString.equals(Environment.MEDIA_MOUNTED)) {
            Log.d("x", "the SDcard mounted");
            return true;
        }
        return false;

    }


    public static long getFreeSpace() {
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());

        long sdFreeMB = stat.getAvailableBlocks() * stat
                .getBlockSize();
        return sdFreeMB;
    }


    public static String getSizeToSting(long size) {

        if (size < SIZE_KB) {
            return size + "B";
        }

        if (size < SIZE_MB) {
            return Math.round(size * 100.0 / SIZE_KB) / 100.0 + "KB";
        }

        if (size < SIZE_GB) {
            return Math.round(size * 100.0 / SIZE_MB) / 100.0 + "MB";
        }

        return Math.round(size * 100.0 / SIZE_GB) / 100.0 + "G";

    }

}

使用

  • 配置缓存设置

  private void config() {
      distory = getContext().getExternalCacheDir().getPath() + File.separator + "filecache";
      LRUFileCache.getInstance().setFileLoadOptions(new FileCacheOptions.Builder()
              .setMaxFileCount(5)
              .setMaxCacheSize(200 * 1024L)
              .setIsUseFileCache(true)
              .setCacheRootPath(distory)
              .builder());
  }

使用

  • 配置缓存设置

  private void config() {
      distory = getContext().getExternalCacheDir().getPath() + File.separator + "filecache";
      LRUFileCache.getInstance().setFileLoadOptions(new FileCacheOptions.Builder()
              .setMaxFileCount(5)
              .setMaxCacheSize(200 * 1024L)
              .setIsUseFileCache(true)
              .setCacheRootPath(distory)
              .builder());
  }
  • 获取文件
 File file =LRUFileCache.getInstance().getDiskFile(url);
 if(file!=null){
    return  file;
 }else{

 //todo  下载
 }
  • API
 // 释放空间
 /**
 * This method will free the files which had not been used at a long time
 */
 LRUFileCache.getInstance().freeSpaceIfNeeded();
 
 

参考文献

Android大图加载优化--基于LRU算法的本地文件缓存

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 161,326评论 4 369
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,228评论 1 304
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,979评论 0 252
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,489评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,894评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,900评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,075评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,803评论 0 205
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,565评论 1 249
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,778评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,255评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,582评论 3 261
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,254评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,151评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,952评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,035评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,839评论 2 277

推荐阅读更多精彩内容