美文网首页
DiskLruCache

DiskLruCache

作者: DeveloperCong | 来源:发表于2017-04-25 15:29 被阅读0次

    1 使用;

    ```

    publicclassBasicCache{

    privateDiskLruCache diskCache;

    privateString fileName ="cache";

    publicBasicCache(String filePath,longmaxDiskSize){

    try{

    diskCache = DiskLruCache.open(newFile(filePath, fileName),1,1, maxDiskSize);

    }catch(IOException exc) {

    diskCache =null;

    }

    }

    /**

    * url转MD5

    *

    *@paramurl

    *@return

    */

    privateStringurlToMD5(HttpUrl url){

    returnMD5.getMD5(url.toString());

    }

    /**

    * 添加缓存数据

    *

    *@paramresponse

    */

    publicvoidaddCache(String date, Response response){

    if(diskCache ==null) {

    return;

    }

    Buffer buffer =newBuffer();

    try{

    buffer.write(date.getBytes());

    byte[] rawResponse = buffer.readByteArray();

    DiskLruCache.Editor editor = diskCache.edit(urlToMD5(response.request().url()));

    editor.set(0,newString(rawResponse, Charset.defaultCharset()));

    editor.commit();

    buffer.clone();

    }catch(IOException exc) {

    buffer.clone();

    }

    }

    /**

    * 获取缓存数据

    *

    *@paramrequest

    *@return

    */

    publicResponseBodygetCache(Request request){

    if(diskCache ==null) {

    returnnull;

    }

    String cacheKey = urlToMD5(request.url());

    try{

    DiskLruCache.Snapshot cacheSnapshot = diskCache.get(cacheKey);

    if(cacheSnapshot !=null) {

    returnResponseBody.create(null, cacheSnapshot.getString(0).getBytes());

    }else{

    returnnull;

    }

    }catch(IOException exc) {

    returnnull;

    }

    }

    /**

    * 删除缓存

    *

    *@paramrequest

    */

    publicvoiddeleteCache(Request request){

    if(diskCache ==null) {

    return;

    }

    try{

    String cacheKey = urlToMD5(request.url());

    DiskLruCache.Snapshot cacheSnapshot = diskCache.get(cacheKey);

    if(cacheSnapshot !=null) {

    diskCache.remove(cacheKey);

    }

    }catch(IOException e) {

    e.printStackTrace();

    }

    }

    }

    ```

    2 源码;

    3 注意事项;

    4 在项目中使用;

    相关文章

      网友评论

          本文标题:DiskLruCache

          本文链接:https://www.haomeiwen.com/subject/dgpvzttx.html