android异步图片加载中的图片缓存

读取大文件流的问题:缓存 开多线程把图片从网络上荡下来以后,首先缓存至本地文件夹 //android.content.ContextWrapper.getCacheDir() android系统提供的一个存放和得到缓存文件夹的方法
然后对文件全路径截取后缀之前的内容进行MD5加密并与后缀拼成一个文件名,根据这个文件名和传入的路径构建一个文件 写一个缓存方法  判断是否存在缓存文件
如果是则返回加密后文件的Uri,如果不是则从网上下载文件并返回文件的Uri.做缓存的目的是用缓存的文件,而Uri就可以唯一标识一个文件。
public static Uri cacheFile(String path,File saveDir)throws Exception{    File file = new File(saveDir, MD5.getMD5(path)+ path.substring(path.lastIndexOf('.')));
    if(file.exists()){
        return Uri.fromFile(file);    
    }else{
        FileOutputStream outStream = new FileOutputStream(file);
        HttpURLConnection conn = (HttpURLConnection)new URL(path).openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode()==200){
            InputStream inStream = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while( (len = inStream.read(buffer)) !=-1 ){
                outStream.write(buffer, 0, len);
            }
            outStream.close();
            inStream.close();
            return Uri.fromFile(file);
        }else{
            throw new Exception("文件下载失败!");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值