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

简介: 零、前言[1]把我的缓存文件工具改写成了策略模式,感觉还不错。[2]以前静态方法调用,很方便,但看着就是不爽,代码真的太冗余了。[3]突然灵光一闪,"少年,看你骨骼惊奇,策略模式了解一下吗。

零、前言

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

缓存策略类图

缓存策略.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");
缓存.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 + "\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;
    }
}
/**
 * 作者:张风捷特烈<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.欢迎关注我的微信公众号,最新精彩文章,及时送达:
公众号.jpg
相关文章
|
14天前
|
Java Android开发 C++
Android Studio JNI 使用模板:c/cpp源文件的集成编译,快速上手
本文提供了一个Android Studio中JNI使用的模板,包括创建C/C++源文件、编辑CMakeLists.txt、编写JNI接口代码、配置build.gradle以及编译生成.so库的详细步骤,以帮助开发者快速上手Android平台的JNI开发和编译过程。
64 1
|
16天前
|
缓存 安全 Android开发
Android经典实战之用Kotlin泛型实现键值对缓存
本文介绍了Kotlin中泛型的基础知识与实际应用。泛型能提升代码的重用性、类型安全及可读性。文中详细解释了泛型的基本语法、泛型函数、泛型约束以及协变和逆变的概念,并通过一个数据缓存系统的实例展示了泛型的强大功能。
26 2
|
18天前
|
缓存 NoSQL Linux
【Azure Redis 缓存】Windows和Linux系统本地安装Redis, 加载dump.rdb中数据以及通过AOF日志文件追加数据
【Azure Redis 缓存】Windows和Linux系统本地安装Redis, 加载dump.rdb中数据以及通过AOF日志文件追加数据
【Azure Redis 缓存】Windows和Linux系统本地安装Redis, 加载dump.rdb中数据以及通过AOF日志文件追加数据
|
14天前
|
开发工具 git 索引
repo sync 更新源码 android-12.0.0_r34, fatal: 不能重置索引文件至版本 ‘v2.27^0‘。
本文描述了在更新AOSP 12源码时遇到的repo同步错误,并提供了通过手动git pull更新repo工具来解决这一问题的方法。
37 1
|
19天前
|
存储 缓存 NoSQL
【Azure Redis 缓存 Azure Cache For Redis】如何设置让Azure Redis中的RDB文件暂留更久(如7天)
【Azure Redis 缓存 Azure Cache For Redis】如何设置让Azure Redis中的RDB文件暂留更久(如7天)
|
27天前
|
缓存 程序员
封装一个给 .NET Framework 用的内存缓存帮助类
封装一个给 .NET Framework 用的内存缓存帮助类
|
12天前
|
存储 监控 数据库
Android经典实战之OkDownload的文件分段下载及合成原理
本文介绍了 OkDownload,一个高效的 Android 下载引擎,支持多线程下载、断点续传等功能。文章详细描述了文件分段下载及合成原理,包括任务创建、断点续传、并行下载等步骤,并展示了如何通过多种机制保证下载的稳定性和完整性。
22 0
|
18天前
|
缓存 NoSQL Redis
【Azure Redis 缓存】Azure Cache for Redis 服务的导出RDB文件无法在自建的Redis服务中导入
【Azure Redis 缓存】Azure Cache for Redis 服务的导出RDB文件无法在自建的Redis服务中导入
|
18天前
|
缓存 NoSQL 算法
【Azure Redis 缓存】Redis导出数据文件变小 / 在新的Redis复原后数据大小压缩近一倍问题分析
【Azure Redis 缓存】Redis导出数据文件变小 / 在新的Redis复原后数据大小压缩近一倍问题分析
|
21天前
|
Android开发 iOS开发
Android项目架构设计问题之将隐式跳转的逻辑进行抽象和封装如何解决
Android项目架构设计问题之将隐式跳转的逻辑进行抽象和封装如何解决
27 0