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 在项目中使用;