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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章