Android 离线缓存之文件缓存

Android 离线缓存之文件缓存

数据缓存到本地,节省用户流量,减少出现加载中或加载失败提示.

缓存数据有很多种方法:

数据库缓存

  • 数据库缓存
  • 文件缓存
  • sharedPreference缓存

各有优缺点,其中文件缓存比较方便快捷.

Activity有context.openFileOutput(file, Context.MODE_PRIVATE)context.openFileInput(file),这两个方法提供了对文件写入和读取的原生支持,减少很多IO流的重复代码.
加上new ObjectOutputStream(fileOutputStream)new ObjectInputStream(fileInputStream)这两个类对对象的序列化提供的支持.
从文件到对象变的非常方便和快捷

以下是代码:

对象的写入:

public void saveCashe(Serializable serializable, String file) {
    FileOutputStream fileOutputStream = null;
    ObjectOutputStream objectOutputStream = null;
    try {
        fileOutputStream = openFileOutput(file, Context.MODE_PRIVATE);
        objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(serializable);
        objectOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            if (objectOutputStream != null) {
                objectOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} 

对象的读取:

public Serializable getCashe(String file) {
    if (!isExitCashe(file)){
        return null;
    }
    FileInputStream fileInputStream = null;
    ObjectInputStream objectInputStream = null;
    try {
        fileInputStream = openFileInput(file);
        objectInputStream = new ObjectInputStream(fileInputStream);
        Object o = objectInputStream.readObject();
        return (Serializable) o;
    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
        if (e instanceof ClassNotFoundException) {
            File fileStreamPath = getFileStreamPath(file);
            fileStreamPath.delete();
        }
    } finally {
        try {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (objectInputStream != null) {
                objectInputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

文件存在与否的判断:

public boolean isExitCashe(String file){
        File fileStreamPath = getFileStreamPath(file);
        return fileStreamPath.exists();
    }

注意

对象需要实现Serializable接口.Map,List默认都实现了Serializable,所以可以直接读取.
getFileOutput()getFileInput()由context提供的支持,其文件存储在Data/Data/包名/file目录下面,只需要传入文件名即可.

以上为所有内容.
文章作者pompip,主要记录和分享coding中经验

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值