android 简单写了一个缓冲图片 json json数组,对象的工具类

本文介绍了一个用于Android应用的缓存管理工具类CacheUtils,它提供了多种数据类型的缓存存储和读取方法,并实现了缓存文件数量及大小的限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<span style="font-size:18px;">package com.zhimore.cache;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.zhimore.cache.utils.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
public class CacheUtils {
	private static final int MAX_SIZE = 1000 * 1000 * 10; // 10 mb
	private static final int MAX_COUNT = Integer.MAX_VALUE; // 不限制存放数据的数量
	private static final String TAG = CacheUtils.class.getSimpleName();
	private static String cacheName = CacheUtils.class.getSimpleName();
	private static Map<String, CacheUtils> mInstanceMap = new HashMap<String, CacheUtils>();
	private CacheManager mCache;
	/**
	 * @param cacheDir
	 * @param maxSize
	 * @param maxCount
	 */
	public CacheUtils(File cacheDir, long maxSize, int maxCount) {
		if(!cacheDir.exists()&&!cacheDir.mkdirs()){
			throw new RuntimeException("can't make dirs in " + cacheDir.getAbsolutePath());
		}
		mCache = new CacheManager(cacheDir, maxSize, maxCount);
	}
	/**
	 * 
	 * @param context 上下文
	 * @return CacheUtils
	 */
	public static CacheUtils get(Context context){
		return get(context,cacheName);
	}
	/**
	 * @param context 上下文
	 * @param cacheName  文件名
	 * @return
	 */
	private static CacheUtils get(Context context, String cacheName) {
		File file = new File(context.getCacheDir(), cacheName);
		return get(file,MAX_SIZE,MAX_COUNT);
	}
	/**
	 * @param file 要保存的文件
	 * @param maxSize 
	 * @param maxCount  
	 * @return 根据文件名返回CacheUtils对象,如果文件名不同 它设置的文件大小 以及文件个数就不同
	 */
	private static CacheUtils get(File cacheDir, long maxSize, int maxCount) {
		CacheUtils manager = mInstanceMap.get(cacheDir.getAbsoluteFile() + myPid());
		if (manager == null) {
			manager = new CacheUtils(cacheDir, maxSize, maxCount);
			mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), manager);
		}
		return manager;
	}
	private static String myPid() {
		return "_" + android.os.Process.myPid();
	}
	/**
	 * 保存string数据到缓存中
	 */
	public void put(String key, String value) {
		File file = mCache.newFile(key);
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter(file), 1024);
			out.write(value);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			mCache.put(file);
		}
	}
	/**
	 * 读取 String数据
	 */
	public  String getAsString(String key) {
		File file = mCache.get(key);
		if (!file.exists())
			return null;
		boolean removeFile = false;
		BufferedReader in = null;
		try {
			in = new BufferedReader(new FileReader(file));
			String readString = "";
			String currentLine;
			while ((currentLine = in.readLine()) != null) {
				readString += currentLine;
			}
			if (!Utils.isDue(readString)) {
				return Utils.clearDateInfo(readString);
			} else {
				removeFile = true;
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (removeFile)
				remove(key);
		}
	}
	/**
	 * 读取Object对象
	 * @param key
	 * @return
	 */
	public Object getAsObject(String key){
		byte[] data = getAsBinary(key);
		if (data != null) {
			ByteArrayInputStream bais = null;
			ObjectInputStream ois = null;
			try {
				bais = new ByteArrayInputStream(data);
				ois = new ObjectInputStream(bais);
				Object reObject = ois.readObject();
				return reObject;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				try {
					if (bais != null)
						bais.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					if (ois != null)
						ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	/**
	 * 获取缓存的json object
	 * @return
	 */
	public  JSONObject getAsJSONObject(String key){
		JSONObject jsonObject = null;
		if(!TextUtils.isEmpty(key)){
			String json = getAsString(key);
			try {
			   jsonObject = new JSONObject(json);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return jsonObject;
	}
	/**
	 * 移除某个key
	 */
	public boolean remove(String key) {
		return mCache.remove(key);
	}
	/**
	 * 缓存管理器
	 */
	class CacheManager{
		protected File cacheDir;
		private final AtomicLong cacheSize;
		private final AtomicInteger cacheCount;
		private final long sizeLimit;
		private final int countLimit;
		private final Map<File, Long> lastUsageDates = Collections.synchronizedMap(new HashMap<File, Long>());
		private CacheManager(File cacheDir, long sizeLimit, int countLimit) {
			this.cacheDir = cacheDir;
			this.sizeLimit = sizeLimit;
			this.countLimit = countLimit;
			cacheSize = new AtomicLong();
			cacheCount = new AtomicInteger();
			calculateCacheSizeAndCacheCount();
		}
		/**
		 * @param key
		 * @return
		 */
		public File newFile(String key) {
			return new File(cacheDir, key.hashCode() + "");
		}
		/**
		 * 保存 String数据 到 缓存中
		 */
		public void put(String key, String value, int saveTime) {
			put(key, Utils.newStringWithDateInfo(saveTime, value));
		}
		/**
		 * 保存 String数据 到 缓存中
		 */
		public void put(String key, String value) {
			File file = mCache.newFile(key);
			BufferedWriter out = null;
			try {
				out = new BufferedWriter(new FileWriter(file), 1024);
				out.write(value);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (out != null) {
					try {
						out.flush();
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				mCache.put(file);
			}
		}
		/**
		 * 保存 byte数据 到 缓存中
		 */
		public void put(String key, byte[] value, int saveTime) {
			put(key, Utils.newByteArrayWithDateInfo(saveTime, value));
		}
		/**
		 * 保存 byte数据 到 缓存中
		 */
		public void put(String key, byte[] value) {
			File file = mCache.newFile(key);
			FileOutputStream out = null;
			try {
				out = new FileOutputStream(file);
				out.write(value);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (out != null) {
					try {
						out.flush();
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				mCache.put(file);
			}
		}
		/**
		 * 把file
		 * @param file
		 */
		private void put(File file) {
			int curCacheCount = cacheCount.get();
			while (curCacheCount + 1 > countLimit) {
				long freedSize = removeNext();
				cacheSize.addAndGet(-freedSize);

				curCacheCount = cacheCount.addAndGet(-1);
			}
			cacheCount.addAndGet(1);

			long valueSize = calculateSize(file);
			long curCacheSize = cacheSize.get();
			while (curCacheSize + valueSize > sizeLimit) {
				long freedSize = removeNext();
				curCacheSize = cacheSize.addAndGet(-freedSize);
			}
			cacheSize.addAndGet(valueSize);

			Long currentTime = System.currentTimeMillis();
			file.setLastModified(currentTime);
			lastUsageDates.put(file, currentTime);
		}
		/**
		 * 计算 cacheSize和cacheCount
		 */
		private void calculateCacheSizeAndCacheCount() {
			new Thread(new Runnable() {
				@Override
				public void run() {
					int size = 0;
					int count = 0;
					File[] cachedFiles = cacheDir.listFiles();
					if (cachedFiles != null) {
						for (File cachedFile : cachedFiles) {
							size += calculateSize(cachedFile);
							count += 1;
							lastUsageDates.put(cachedFile, cachedFile.lastModified());
						}
						cacheSize.set(size);
						cacheCount.set(count);
					}
				}
			}).start();
		}
		/**
		 * 移除旧的文件
		 * 
		 * @return
		 */
		private long removeNext() {
			if (lastUsageDates.isEmpty()) {
				return 0;
			}

			Long oldestUsage = null;
			File mostLongUsedFile = null;
			Set<Entry<File, Long>> entries = lastUsageDates.entrySet();
			synchronized (lastUsageDates) {
				for (Entry<File, Long> entry : entries) {
					if (mostLongUsedFile == null) {
						mostLongUsedFile = entry.getKey();
						oldestUsage = entry.getValue();
					} else {
						Long lastValueUsage = entry.getValue();
						if (lastValueUsage < oldestUsage) {
							oldestUsage = lastValueUsage;
							mostLongUsedFile = entry.getKey();
						}
					}
				}
			}

			long fileSize = calculateSize(mostLongUsedFile);
			if (mostLongUsedFile.delete()) {
				lastUsageDates.remove(mostLongUsedFile);
			}
			return fileSize;
		}
		/**
		 * 根据key删除文件
		 * @param key
		 * @return
		 */
		private boolean remove(String key) {
			File image = get(key);
			return image.delete();
		}

		/**
		 * 根据key获取文件
		 * @param key
		 * @return
		 */
		private File get(String key) {
			File file = newFile(key);
			Long currentTime = System.currentTimeMillis();
			file.setLastModified(currentTime);
			lastUsageDates.put(file, currentTime);

			return file;
		}
		private long calculateSize(File file) {
			return file.length();
		}
	}
	/**
	 * @param key 
	 * @param jsonObject json object对象
	 */
	public void put(String key, JSONObject jsonObject) {
		if(jsonObject!=null){
			put(key, jsonObject.toString());
		}
	}
	/**
	 * @param key 
	 * @param jsonArray 字符串数组
	 */
	public void put(String key, JSONArray jsonArray) {
		if(jsonArray!=null){
			put(key, jsonArray.toString());
		}
	}
	/**
	 * 保存 byte数据 到 缓存中
	 */
	public void put(String key, byte[] value) {
		File file = mCache.newFile(key);
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			out.write(value);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			mCache.put(file);
		}
	}
	/**
	 * 缓存图片
	 * @param name
	 * @param bitmap
	 */
	public void put(String key, Bitmap bitmap) {
		put(key, Utils.Bitmap2Bytes(bitmap));
	}
	public Bitmap getAsBitmap(String key){
		if (getAsBinary(key) == null) {
			return null;
		}
		return Utils.Bytes2Bimap(getAsBinary(key));
		
	}
	/**
	 * 获取 byte 数据
	 */
	public byte[] getAsBinary(String key) {
		RandomAccessFile RAFile = null;
		boolean removeFile = false;
		try {
			File file = mCache.get(key);
			if (!file.exists())
				return null;
			RAFile = new RandomAccessFile(file, "r");
			byte[] byteArray = new byte[(int) RAFile.length()];
			RAFile.read(byteArray);
			if (!Utils.isDue(byteArray)) {
				return Utils.clearDateInfo(byteArray);
			} else {
				removeFile = true;
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (RAFile != null) {
				try {
					RAFile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (removeFile)
				remove(key);
		}
	}
	/**
	 * @param key
	 * @param person
	 */
	public void put(String key, Serializable value) {
		if(value!=null){
			put(key, value, -1);
		}
	}
	/**
	 * 保存 Serializable数据到 缓存中 前提这个对象要序列化
	 */
	public void put(String key, Serializable value, int saveTime) {
		ByteArrayOutputStream baos = null;
		ObjectOutputStream oos = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(value);
			byte[] data = baos.toByteArray();
			if (saveTime != -1) {
				put(key, data, saveTime);
			} else {
				put(key, data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				oos.close();
			} catch (IOException e) {
			}
		}
	}
	/**
	 * @param key
	 * @param drawable
	 */
	public void put(String key, Drawable drawable) {
		Log.e(TAG, "drawable--------->"+drawable);
		if(drawable!=null){
			put(key, Utils.drawable2Bitmap(drawable));
		}
	}
	/**
	 * 读取 Drawable 数据
	 */
	public Drawable getAsDrawable(String key) {
		if (getAsBinary(key) == null) {
			return null;
		}
		return Utils.bitmap2Drawable(Utils.Bytes2Bimap(getAsBinary(key)));
	}
}</span>



用到的工具类:

package com.zhimore.cache.utils;
import java.io.ByteArrayOutputStream;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;


public  class Utils {


/**
* 判断缓存的String数据是否到期
* 
* @param str
* @return true:到期了 false:还没有到期
*/
public static boolean isDue(String str) {
return isDue(str.getBytes());
}


/**
* 判断缓存的byte数据是否到期
* 
* @param data
* @return true:到期了 false:还没有到期
*/
public static boolean isDue(byte[] data) {
String[] strs = getDateInfoFromDate(data);
if (strs != null && strs.length == 2) {
String saveTimeStr = strs[0];
while (saveTimeStr.startsWith("0")) {
saveTimeStr = saveTimeStr.substring(1, saveTimeStr.length());
}
long saveTime = Long.valueOf(saveTimeStr);
long deleteAfter = Long.valueOf(strs[1]);
if (System.currentTimeMillis() > saveTime + deleteAfter * 1000) {
return true;
}
}
return false;
}


public static String newStringWithDateInfo(int second, String strInfo) {
return createDateInfo(second) + strInfo;
}


public static byte[] newByteArrayWithDateInfo(int second, byte[] data2) {
byte[] data1 = createDateInfo(second).getBytes();
byte[] retdata = new byte[data1.length + data2.length];
System.arraycopy(data1, 0, retdata, 0, data1.length);
System.arraycopy(data2, 0, retdata, data1.length, data2.length);
return retdata;
}


public static String clearDateInfo(String strInfo) {
if (strInfo != null && hasDateInfo(strInfo.getBytes())) {
strInfo = strInfo.substring(strInfo.indexOf(mSeparator) + 1, strInfo.length());
}
return strInfo;
}


public static byte[] clearDateInfo(byte[] data) {
if (hasDateInfo(data)) {
return copyOfRange(data, indexOf(data, mSeparator) + 1, data.length);
}
return data;
}


public static boolean hasDateInfo(byte[] data) {
return data != null && data.length > 15 && data[13] == '-' && indexOf(data, mSeparator) > 14;
}


public static String[] getDateInfoFromDate(byte[] data) {
if (hasDateInfo(data)) {
String saveDate = new String(copyOfRange(data, 0, 13));
String deleteAfter = new String(copyOfRange(data, 14, indexOf(data, mSeparator)));
return new String[] { saveDate, deleteAfter };
}
return null;
}


public static int indexOf(byte[] data, char c) {
for (int i = 0; i < data.length; i++) {
if (data[i] == c) {
return i;
}
}
return -1;
}


public static byte[] copyOfRange(byte[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
byte[] copy = new byte[newLength];
System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength));
return copy;
}


public static final char mSeparator = ' ';
private static final String TAG = Utils.class.getSimpleName();


public static String createDateInfo(int second) {
String currentTime = System.currentTimeMillis() + "";
while (currentTime.length() < 13) {
currentTime = "0" + currentTime;
}
return currentTime + "-" + second + mSeparator;
}


/*
* Bitmap → byte[]
*/
public static byte[] Bitmap2Bytes(Bitmap bm) {
if (bm == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}


/*
* byte[] → Bitmap
*/
public static Bitmap Bytes2Bimap(byte[] b) {
if (b.length == 0) {
return null;
}
return BitmapFactory.decodeByteArray(b, 0, b.length);
}


/*
* Drawable → Bitmap
*/
public static  Bitmap drawable2Bitmap(Drawable drawable) {
Log.e(TAG, "drawable-------->"+drawable);
if (drawable == null) {
return null;
}
// 取 drawable 的长宽
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();
// 取 drawable 的颜色格式
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
// 建立对应 bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// 建立对应 bitmap 的画布
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// 把 drawable 内容画到画布中
drawable.draw(canvas);
Log.e(TAG, "bitmap-------->"+bitmap);
return bitmap;
}


/*
* Bitmap → Drawable
*/
@SuppressWarnings("deprecation")
public static Drawable bitmap2Drawable(Bitmap bm) {
if (bm == null) {
return null;
}
BitmapDrawable bd=new BitmapDrawable(bm);
bd.setTargetDensity(bm.getDensity());
return new BitmapDrawable(bm);
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值