根据开源小项目 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("[+]+", "+");
}
}
}