使用Lrucache缓存



public class FileLoader {

    /**
     * 定义缓存对象
     */
    public LruCache<String, File> fileLruCache;

    public FileLoader(){
        if (fileLruCache == null){
            //获取应用内存空间
            long maxMemory = Runtime.getRuntime().maxMemory();
            //获取到最大的缓存空间
            int cacheSize = (int) (maxMemory / 8);
            //创建缓存对象
            fileLruCache = new LruCache<String, File>(cacheSize){
                @Override
                protected int sizeOf(String key, File value) {
                    return super.sizeOf(key, value);
                }
            };
        }
    }

    /**
     * 实现添加到缓存中
     * @param key
     * @param file
     */
    public void addFileToCache(String key, File file){
        if (getFileFromCache(key) == null){
            fileLruCache.put(key, file);
        }
    }

    /**
     * 从缓冲中获取文件
     * @param key
     * @return
     */
    public File getFileFromCache(String key){
        if (fileLruCache != null){
            return fileLruCache.get(key);
        }
        return null;
    }

    /**
     * 从缓存中移除文件
     * @param key
     */
    public void removeFromCache(String key){
        if (fileLruCache != null){
            fileLruCache.remove(key);
        }
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容