外部文件緩存
[html] view plaincopy
private File mCacheDir = context.getCacheDir();
private static final int MAX_CACHE_SIZE = 20 * 1024 * 1024; //20M
private final LruCache sFileCache = new LruCache(MAX_CACHE_SIZE){
@Override
public int sizeOf(String key, Long value){
return value.intValue();
}
@Override
protected void entryRemoved(boolean evicted, String key, Long oldValue, Long newValue){
File file = getFile(key);
if(file != null)
file.delete();
}
}
private File getFile(String fileName) throws FileNotFoundException {
File file = new File(mCacheDir, fileName);
if(!file.exists() || !file.isFile())
throw new FileNotFoundException("文件不存在或有同名文件夾");
return file;
}
//緩存bitmap到外部存儲
public boolean putBitmap(String key, Bitmap bitmap){
File file = getFile(key);
if(file != null){
Log.v("tag", "文件已經存在");
return true;
}
FileOutputStream fos = getOutputStream(key);
boolean saved = bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
if(saved){
synchronized(sFileCache){
sFileCache.put(key, getFile(key).length());
}
return true;
}
return false;
}
//根據key獲取OutputStream
private FileOutputStream getOutputStream(String key){
if(mCacheDir == null)
return null;
FileOutputStream fos = new FileOutputStream(mCacheDir.getAbsolutePath() + File.separator + key);
return fos;
}
//獲取bitmap
private static BitmapFactory.Options sBitmapOptions;
static {
sBitmapOptions = new BitmapFactory.Options();
sBitmapOptions.inPurgeable=true; //bitmap can be purged to disk
}
public Bitmap getBitmap(String key){
File bitmapFile = getFile(key);
if(bitmapFile != null){
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(bitmapFile), null, sBitmapOptions);
if(bitmap != null){
//重新將其緩存至硬引用中
...
}
}
}