DiskLruCache简介
GitHub:https://github.com/JakeWharton/DiskLruCache
APIDoc:http://jakewharton.github.io/DiskLruCache/
- 缓存的
key
为String
类型,且必须匹配正则表达式[a-z0-9_-]{1,64}
;- 一个key可以对应多个value,
value
类型为字节数组,大小在0 ~ Integer.MAX_VALUE
之间;- 缓存的目录必须为专用目录,因为DiskLruCache可能会删除或覆盖该目录下的文件。
- 添加缓存操作具备原子性,但多个进程不应该同时使用同一个缓存目录。
添加依赖
// add dependence
implementation 'com.jakewharton:disklrucache:2.0.2'
创建DiskLruCache对象
/*
* directory – 缓存目录
* appVersion - 缓存版本
* valueCount – 每个key对应value的个数
* maxSize – 缓存大小的上限
*/
DiskLruCache diskLruCache = DiskLruCache.open(directory, 1, 1, 1024 * 1024 * 10);
添加 / 获取 缓存(一对一)
/**
* 添加一条缓存,一个key对应一个value
*/
public void addDiskCache(String key, String value) throws IOException {
File cacheDir = context.getCacheDir();
DiskLruCache diskLruCache = DiskLruCache.open(cacheDir, 1, 1, 1024 * 1024 * 10);
DiskLruCache.Editor editor = diskLruCache.edit(key);
// index与valueCount对应,分别为0,1,2...valueCount-1
editor.newOutputStream(0).write(value.getBytes());
editor.commit();
diskLruCache.close();
}
/**
* 获取一条缓存,一个key对应一个value
*/
public void getDiskCache(String key) throws IOException {
File directory = context.getCacheDir();
DiskLruCache diskLruCache = DiskLruCache.open(directory, 1, 1, 1024 * 1024 * 10);
String value = diskLruCache.get(key).getString(0);
diskLruCache.close();
}
添加 / 获取 缓存(一对多)
/**
* 添加一条缓存,1个key对应2个value
*/
public void addDiskCache(String key, String value1, String value2) throws IOException {
File directory = context.getCacheDir();
DiskLruCache diskLruCache = DiskLruCache.open(directory, 1, 2, 1024 * 1024 * 10);
DiskLruCache.Editor editor = diskLruCache.edit(key);
editor.newOutputStream(0).write(value1.getBytes());
editor.newOutputStream(1).write(value2.getBytes());
editor.commit();
diskLruCache.close();
}
/**
* 添加一条缓存,1个key对应2个value
*/
public void getDiskCache(String key) throws IOException {
File directory = context.getCacheDir();
DiskLruCache diskLruCache = DiskLruCache.open(directory, 1, 2, 1024);
DiskLruCache.Snapshot snapshot = diskLruCache.get(key);
String value1 = snapshot.getString(0);
String value2 = snapshot.getString(1);
diskLruCache.close();
}
网友评论