介绍
android中向本地存放数据的方式有,数据库,sharedpreference和文件。如果想提出一个能用于存放缓存的话,数据库需要建立相应的表格,sharedPreference好像不可以,文件的话,用序列化就可以。所以就采用文件的方式。
问题
采用文件存放缓存有一个问题,就是有些对象是不能被序列化的,比如bitmap。我采用的方法就是,将这些对象前面加上transient标记,在反序列化的时候将这样的对象用能序列化的对象(比如图片的路径)新建出来。好吧,贴个能在本地做缓存的模版
解决
/**
* 用于做本地缓存,T需要覆盖equals()方法和hashCode()方法
*/
public class BufferStore<T extends Serializable & Comparable<T>> {
private final String mBuffPath;
/**
* @param buffPath
* 存放缓存的路径
* */
public BufferStore(String buffPath) {
mBuffPath = buffPath;
}
/**
* @param list
* 向本地写入的缓存数据
* @param maxCount
* 本地缓存的最大数据量
* */
public synchronized void write(List<T> list, int maxCount) {
if (list == null || maxCount <= 0) {
return;
}
// 获得缓存数据
List<T> oldList = get();
// 将新数据加入
for (T t : list) {
// 不存在才加入
if (!oldList.contains(t)) {
oldList.add(t);
}
}
// 将数据排序
Collections.sort(oldList);
// 删除多余数据
for (int i = oldList.size() - 1; i >= maxCount; i--) {
oldList.remove(i);
}
// 写入本地
put(oldList);
}
/**
* 读取缓存数据
*
* @return 缓存数据,数据为空时返回长度为0的list
* */
public synchronized List<T> read() {
return get();
}
/**
* 向本地写入数据
* */
private void put(List<T> list) {
try {
// 打开文件
FileOutputStream fos = new FileOutputStream(mBuffPath);
// 将数据写入文件
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
// 释放资源
oos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 从本地读取数据
* */
@SuppressWarnings("unchecked")
private List<T> get() {
List<T> list = new ArrayList<T>();
try {
File file = new File(mBuffPath);
if (!file.exists()) {
return list;
}
// 打开文件
FileInputStream fis = new FileInputStream(mBuffPath);
// 读取文件
ObjectInputStream ois = new ObjectInputStream(fis);
list = (List<T>) ois.readObject();
// 释放资源
ois.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return list;
}
}
其中read和write是读写方法。write中有个maxCount值是用来指定缓存中最多缓存多少条的。为什么T要实现Comparable?缓存需要按照时间排序。
总结
实现了一个能在本地缓存任意实现了Serializable和Compareable同时覆盖equals()方法的类的工具。