簡單緩存類

根據開源小項目 smartimageview 修改。 基本上照抄了過來。可以緩存json。

分爲內存緩存 和 硬盤緩存 。


package com.hanya.financing.global.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.SoftReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.hanya.financing.imagecache.CacheName;

public class HXCache {

	private static final String DISK_CACHE_PATH = "/json_cache/";
	/**
	 * 內存緩存
	 */
	private ConcurrentHashMap<String, SoftReference<JSONObject>> memoryCache;
	/**
	 * 硬盤緩存 目錄
	 */
	private String diskCachePath;
	private boolean diskCacheEnabled = false;
	/**
	 * 讀寫數據線程
	 */
	private ExecutorService writeThread;

	private HXCache(Context context) {
		memoryCache = new ConcurrentHashMap<String, SoftReference<JSONObject>>();

		// 設置 硬盤緩存的 路徑
		Context appContext = context.getApplicationContext();
		diskCachePath = appContext.getCacheDir().getAbsolutePath()
				+ DISK_CACHE_PATH;
		// 創建緩存目錄
		File outFile = new File(diskCachePath);
		outFile.mkdirs();
		diskCacheEnabled = outFile.exists();
		// 單線程池
		// Set up threadpool for image fetching tasks
		writeThread = Executors.newSingleThreadExecutor();
	}

	private static HXCache cache = null;
	public static HXCache getInstance(Context c){
		synchronized (HXCache.class){
			if (cache == null) {
				cache = new HXCache(c);
			}
		}
		return cache;
	}
	/**
	 * 從緩存獲取數據
	 * 
	 * @param key
	 * @return
	 */
	public JSONObject get(final String key) {
		JSONObject data = null;
		// 首先從內存獲取
		data = getFileFromMemory(key);
		// 其次 從硬盤獲取
		if (data == null) {
			data = getFileFromDisk(key);
			// 並再次 緩存到 內存
			if (data != null) {
				cacheFileToMemory(key, data);
			}
		}
		return data;
	}

	/**
	 * 緩存數據到 內存和硬盤
	 * 
	 * @param key
	 * @param data
	 */
	public void put(String key, JSONObject data) {
		cacheFileToMemory(key, data);
		cacheFileToDisk(key, data);
	}

	/**
	 * 刷新緩存
	 * @param key  索引
	 * @param data  數據
	 */
	public void refresh(String key, JSONObject data){
		remove(key);
		cacheFileToMemory(key, data);
		cacheFileToDisk(key, data);
	}

	/**
	 * 從緩存中刪除數據
	 * 
	 * @param key
	 */
	public void remove(String key) {
		if (key == null) {
			return;
		}

		// 從內存刪除
		memoryCache.remove(getCacheKey(key));

		// 從硬盤刪除
		File f = new File(diskCachePath, getCacheKey(key));
		if (f.exists() && f.isFile()) {
			f.delete();
		}
	}

	/**
	 * 清除所有緩存
	 */
	public void clear() {
		// Remove all from memory cache
		memoryCache.clear();

		// Remove all from file cache
		File cachedFileDir = new File(diskCachePath);
		if (cachedFileDir.exists() && cachedFileDir.isDirectory()) {
			File[] cachedFiles = cachedFileDir.listFiles();
			for (File f : cachedFiles) {
				if (f.exists() && f.isFile()) {
					f.delete();
				}
			}
		}
	}

	/**
	 * 緩存 數據到內存 的實現
	 * 
	 * @param key
	 * @param data
	 */
	private void cacheFileToMemory(final String key, final JSONObject data) {
		memoryCache.put(getCacheKey(key), new SoftReference<JSONObject>(data));
	}

	/**
	 * 緩存數據到硬盤
	 * 
	 * @param key
	 * @param data
	 */
	private void cacheFileToDisk(final String key, final JSONObject data) {

		if (data == null || data.length() == 0) {
			return;
		}
		final byte[] byteData = data.toString().getBytes();
		writeThread.execute(new Runnable() {

			@Override
			public void run() {
				if (diskCacheEnabled) {
					FileOutputStream ostream = null;
					try {
						ostream = new FileOutputStream(new File(diskCachePath,
								getCacheKey(key)));
						ostream.write(byteData, 0, byteData.length);
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						try {
							if (ostream != null) {
								ostream.flush();
								ostream.close();
							}
						} catch (IOException e) {
						}
					}
				}
			}
		});

	}

	private JSONObject getFileFromMemory(String key) {

		JSONObject data = null;
		SoftReference<JSONObject> softRef = memoryCache.get(getCacheKey(key));
		if (softRef != null) {
			data = softRef.get();
		}

		return data;

	}

	private JSONObject getFileFromDisk(String key) {

		JSONObject data = null;
		if (diskCacheEnabled) {
			String filePath = getFilePath(key);
			File file = new File(filePath);
			if (file.exists()) {
				BufferedReader br = null;
				try {
					br = new BufferedReader(new InputStreamReader(
							new FileInputStream(file)));
					String temp = null;
					StringBuffer sb = new StringBuffer();
					temp = br.readLine();
					while (temp != null) {
						sb.append(temp);
						temp = br.readLine();
					}
					data = new JSONObject(sb.toString());
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				} finally {
					try {
						if (br != null)
							br.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				return data;

			}
		}
		return data;

	}

	private String getFilePath(String url) {
		return diskCachePath + getCacheKey(url);
	}

	private String getCacheKey(String url) {
		if (url == null) {
			throw new RuntimeException("Null url passed in");
		} else {
			return url.replaceAll("[.:/,%?&=]", "+").replaceAll("[+]+", "+");
		}
	}
}












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