前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >4-SII--☆Android缓存文件(带有效时长)封装

4-SII--☆Android缓存文件(带有效时长)封装

作者头像
张风捷特烈
发布2018-09-26 16:29:34
4190
发布2018-09-26 16:29:34
举报
零、前言

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

缓存策略.png

一、使用:
代码语言:javascript
复制
        //新建缓存对象
        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");

缓存.png

本文由张风捷特烈原创,转载请注明 更多安卓技术欢迎访问:https://www.jianshu.com/c/004f3fe34c94 张风捷特烈个人网站,编程笔记请访问:http://www.toly1994.com 你的喜欢与支持将是我最大的动力

二、附录:各类及实现
代码语言:javascript
复制
/**
 * 作者:张风捷特烈<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);

}
代码语言:javascript
复制
/**
 * 作者:张风捷特烈<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 + "\n");// 在第一行写入缓存时间, 换行
            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;
    }
}
代码语言:javascript
复制
/**
 * 作者:张风捷特烈<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());
    }
}
代码语言:javascript
复制
/**
 * 作者:张风捷特烈<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");
    }
}
代码语言:javascript
复制
/**
 * 作者:张风捷特烈<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;
    }
}
代码语言:javascript
复制
/**
 * 作者:张风捷特烈<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;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.08.26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 零、前言
  • 一、使用:
  • 二、附录:各类及实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档