Android项目之ImageLoader_磁盘缓存

磁盘缓存采用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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值