android存放本地数据

介绍

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()方法的类的工具。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值