引言
这篇文章主要介绍 android存储文件的轻量级缓存框架 ACache;
原链接地址
库很小,小到只有一个文件,看到源码设计的很精美,决定写篇博客记录一下;
ACache
代码很简洁,只摘要几个亮点以飨文章:
支持多进程下的存储
//设置最大存储空间和最大存储数量;
public static ACache get(File cacheDir, long max_zise, int max_count) {
ACache manager = mInstanceMap.get(cacheDir.getAbsoluteFile() + myPid());
if (manager == null) {
manager = new ACache(cacheDir, max_zise, max_count);
mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), manager);
}
return manager;
}
private static String myPid() {
return "_" + android.os.Process.myPid();
}
存 - 所有被存储的对象都通过 流FileOutputStream 存于本地
key: string的hashcode;
value: 所有的存储对象最后都转化为File 存于缓存目录;
//存于本地路径,同时也是内存缓存中的key,代表文件系统中的路径;
private File newFile(String key) {
return new File(cacheDir, key.hashCode() + "");
}
//string 存储通过hashcode在存储目录中生成一个文件存储;成功后在内存中存储filekey和当前时间long;
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);
}
}
//cachemanager 的put方法
private void put(File file) {
//线程安全Integer;
int curCacheCount = cacheCount.get();
while (curCacheCount + 1 > countLimit) {