zoukankan      html  css  js  c++  java
  • 4-SII--☆Android缓存文件(带有效时长)封装

    零、前言

    [1]把我的缓存文件工具改写成了策略模式,感觉还不错。
    [2]以前静态方法调用,很方便,但看着就是不爽,代码真的太冗余了。
    [3]突然灵光一闪,"少年,看你骨骼惊奇,策略模式了解一下吗。"便有此文。
    [4]如果不了解SharedPreferences,可以先看这篇:1-SII--SharedPreferences完美封装

    缓存策略类图

    9414344-2b6a9f99d052c8a5.png
    缓存策略.png

    一、使用:

            //新建缓存对象
            CacheWorker innerCache = new CacheWorker(new InnerFileStrategy(this));
            //设置缓存
            innerCache.setCache("toly", "hehe", 10);
            //获取缓存
            String value = innerCache.getCache("toly");
    
            //SD卡缓存
            CacheWorker sdCache = new CacheWorker(new SDFileStrategy());
            sdCache.setCache("toly", "hehe2", 10);
            String sdCach = sdCache.getCache("toly");
    
            //SharedPreferences
            CacheWorker spCache = new CacheWorker(new SPStrategy(this));
            spCache.setCache("toly1994.com", "{name:toly}", 10);
            String spValue = spCache.getCache("toly1994.com");
    
    9414344-8f34992d0a3eca32.png
    缓存.png

    二、附录:各类及实现

    /**
     * 作者:张风捷特烈<br/>
     * 时间:2018/8/26 0026:6:20<br/>
     * 邮箱:1981462002@qq.com<br/>
     * 说明:缓存策略接口
     */
    public interface CacheStrategy {
        /**
         * 存储缓存
         * @param key 文件名
         * @param value 文件内容
         * @param time 有效时间 单位:小时
         */
        void setCache(String key, String value,long time);
    
        /**
         * 获取缓存
         * @param key 文件名
         * @return 文件内容
         */
        String getCache(String key);
    
    }
    
    /**
     * 作者:张风捷特烈<br/>
     * 时间:2018/8/26 0026:6:38<br/>
     * 邮箱:1981462002@qq.com<br/>
     * 说明:文件缓存基类
     */
    public abstract class BaseFileStrategy implements CacheStrategy {
        /**
         * 缓存文件的文件夹名称
         */
        private String mDirName;
    
        /**
         * 构造函数
         * @param dirName 缓存文件的文件夹名称
         */
        public BaseFileStrategy(String dirName) {
            mDirName = dirName;
        }
    
        @Override
        public void setCache(String key, String value, long time) {
            // 以url为文件名, 以json为文件内容,保存在本地
            // 生成缓存文件
            File cacheFile = new File(mDirName + File.separator + Md5Util.getMD5(key));
            FileWriter writer = null;
    
            try {
                if (!cacheFile.exists()) {
                    cacheFile.getParentFile().mkdirs();
                    cacheFile.createNewFile();
                }
                writer = new FileWriter(cacheFile);
                // 缓存失效的截止时间
                long deadline = System.currentTimeMillis() + time * 60 * 60 * 1000;//有效期
                writer.write(deadline + "
    ");// 在第一行写入缓存时间, 换行
                writer.write(value);// 写入文件
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.close(writer);
            }
        }
    
        @Override
        public String getCache(String key) {
            // 生成缓存文件
            File cacheFile = new File(mDirName + File.separator + Md5Util.getMD5(key));
            // 判断缓存是否存在
            if (cacheFile.exists()) {
                // 判断缓存是否有效
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader(cacheFile));
                    String deadline = reader.readLine();// 读取第一行的有效期
                    long deadTime = Long.parseLong(deadline);
    
                    if (System.currentTimeMillis() < deadTime) {// 当前时间小于截止时间,
                        // 说明缓存有效
                        // 缓存有效
                        StringBuilder sb = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line);
                        }
                        return sb.toString();
                    } else {
                        setCache(key, "", 0);//缓存过期清空
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    IOUtils.close(reader);
                }
            }
            return null;
        }
    }
    
    /**
     * 作者:张风捷特烈<br/>
     * 时间:2018/8/26 0026:6:28<br/>
     * 邮箱:1981462002@qq.com<br/>
     * 说明:以文件保存缓存 到本包 <br/>
     */
    public class InnerFileStrategy extends BaseFileStrategy {
    
        public InnerFileStrategy(Context context) {
            super(context.getCacheDir().getPath());
        }
    }
    
    /**
     * 作者:张风捷特烈<br/>
     * 时间:2018/8/26 0026:6:28<br/>
     * 邮箱:1981462002@qq.com<br/>
     * 说明:以文件保存缓存 到SD卡cacheData目录 <br/>
     */
    public class SDFileStrategy extends BaseFileStrategy {
    
        public SDFileStrategy() {
            super(Environment.getExternalStorageDirectory() +"/cacheData");
        }
    }
    
    /**
     * 作者:张风捷特烈<br/>
     * 时间:2018/8/26 0026:8:03<br/>
     * 邮箱:1981462002@qq.com<br/>
     * 说明:SharedPreferences缓存
     */
    public class SPStrategy implements CacheStrategy {
    
        private Context mContext;
    
        public SPStrategy(Context context) {
            mContext = context;
        }
    
        @Override
        public void setCache(String key, String value, long time) {
            SpUtils<String> spString= new SpUtils<>(mContext);
            spString.put(key, value);
    
            SpUtils<Long> spLong = new SpUtils<>(mContext);
            spLong.put("LiftTime", System.currentTimeMillis() + time * 60 * 60 * 1000);
        }
    
        @Override
        public String getCache(String key) {
            SpUtils<Long> spLong = new SpUtils<>(mContext);
            Long liftTime = spLong.get("LiftTime", 0L);
            if (System.currentTimeMillis() < liftTime) {// 当前时间小于截止时间,
                SpUtils<String> spString= new SpUtils<>(mContext);
                return spString.get(key, "");
            }else {
                setCache(key, "", 0);//缓存过期清空
            }
            return null;
        }
    }
    
    
    /**
     * 作者:张风捷特烈<br/>
     * 时间:2018/8/26 0026:6:23<br/>
     * 邮箱:1981462002@qq.com<br/>
     * 说明:缓存工作类
     */
    public class CacheWorker {
        /**
         * 缓存策略
         */
        private CacheStrategy mCacheStrategy;
    
        /**
         * 无参构造
         */
        public CacheWorker() {
        }
    
        /**
         * 一参构造
         * @param cacheStrategy 缓存策略
         */
        public CacheWorker(CacheStrategy cacheStrategy) {
            mCacheStrategy = cacheStrategy;
        }
    
        /**
         * 存储缓存
         * @param key 文件名
         * @param value 文件内容
         * @param time 有效时间 单位:小时
         */
        public void setCache(String key, String value, long time) {
            mCacheStrategy.setCache(key, value, time);
        }
    
        /**
         * 获取缓存
         * @param key 文件名
         * @return 文件内容
         */
        public String getCache(String key) {
            return mCacheStrategy.getCache(key);
        }
    
        /**
         * 设置缓存策略
         * @param cacheStrategy 缓存策略
         */
        public void setCacheStrategy(CacheStrategy cacheStrategy) {
            mCacheStrategy = cacheStrategy;
        }
    }
    

    后记、

    1.声明:

    [1]本文由张风捷特烈原创,转载请注明
    [2]欢迎广大编程爱好者共同交流
    [3]个人能力有限,如有不正之处欢迎大家批评指证,必定虚心改正
    [4]你的喜欢与支持将是我最大的动力

    2.连接传送门:

    更多安卓技术欢迎访问:安卓技术栈
    我的github地址:欢迎star
    简书首发,腾讯云+社区同步更新
    张风捷特烈个人网站,编程笔记请访问:http://www.toly1994.com

    3.联系我

    QQ:1981462002
    邮箱:1981462002@qq.com
    微信:zdl1994328

    4.欢迎关注我的微信公众号,最新精彩文章,及时送达:
    9414344-c474349cd3bd4b82.jpg
    公众号.jpg
  • 相关阅读:
    PL/SQL中关于时间的操作
    PL/SQL中关于时间的操作
    Master Data Service调用API创建Model
    ASP.NET Postback回调后参数无效
    Silverlight读取Web.config配置文件
    WCF的用户名+密码认证方式
    Trac 经验谈之(5)插件篇
    Cython 0.15,用 OpenMP 并行多核加速 Python!
    BizTalk Accelerator for HL7医疗行业消息路由处理机制
    Silverlight信息加密 通过Rfc2898DeriveBytes类使用基于HMACSHA1的伪随机数生成器实现PBKDF2
  • 原文地址:https://www.cnblogs.com/toly-top/p/9781937.html
Copyright © 2011-2022 走看看