磁盘缓存采用DiskLruCache类。
public class BitmapDiskCache implements BitmapLruCache {
private int maxSize;
private DiskLruCache diskLruCache;
public BitmapDiskCache(String directoryPath, int maxSize) throws IOException {
this.maxSize = maxSize;
File directory = new File(directoryPath);
diskLruCache = DiskLruCache.open(directory, 1, 1, maxSize);//磁盘存放路径,版本号(版本号更改所有数据清空),每个key所对应的value数,磁盘缓存大小
}
@Override
public synchronized void put(String key, Bitmap value) {
try {
DiskLruCache.Editor edit = diskLruCache.edit(key);//得到key对应的编辑器
if(edit != null) {
OutputStream newOutputStream = edit.newOutputStream(0);//编辑器的输出流 0代表数组index因为value只有一个
value.compress(CompressFormat.JPEG, 90, newOutputStream);//将压缩图片的输出流输出到编辑器的输出流(90代表压缩后的品质为原图的90%)
edit.commit();//一定要提交否则保存失败
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public synchronized Bitmap get(String key) {
Bitmap bitmap = null;
DiskLruCache.Snapshot snapshot = null;
try {
snapshot = diskLruCache.get(key);//得到key的快照
if(snapshot != null) {
InputStream inputStream = snapshot.getInputStream(0);//0代表数组index因为value只有一个
bitmap = BitmapFactory.decodeStream(inputStream);
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
if(snapshot != null)
snapshot.close();
}
return bitmap;
}
@Override
public synchronized void remove(String key) {
try {
diskLruCache.remove(key);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public synchronized void clear() {
try {
diskLruCache.setMaxSize(0);//先设置大小再清除
diskLruCache.flush();
diskLruCache.setMaxSize(maxSize);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public synchronized int getMaxSize() {
return maxSize;
}
@Override
public synchronized int getCurrentSize() {
return (int) diskLruCache.size();//当前缓存的大小 清除app缓存功能可用此方法
}
@Override
public synchronized List<String> getAllKey() {
return diskLruCache.getAllKey();
}
}