我使用Jake Wharton的DiskLruCache在android上实现了文件缓存。这是我对缓存的实现:
@Override
protected FileInputStream doInBackground(String... params) {
String data = params[0];
// Application class where i did open DiskLruCache
DiskLruCache cache = MyApplication.getDiskCache(context);
if (cache == null)
return null;
String key = hashKeyForDisk(data);
final int DISK_CACHE_INDEX = 0;
long currentMaxSize = cache.getMaxSize();
float percentageSize = Math.round((cache.size() * 100.0f) / currentMaxSize);
if (percentageSize >= 90) // cache size reaches 90%
cache.setMaxSize(currentMaxSize + (10 * 1024 * 1024)); // increase size to 10MB
try {
DiskLruCache.Snapshot snapshot = cache.get(key);
if (snapshot == null) {
Log.i(getTag(), "Snapshot is not available downloading...");
DiskLruCache.Editor editor = cache.edit(key);
if (editor != null) {
if (downloadUrlToStream(data, editor.newOutputStream(DISK_CACHE_INDEX)))
editor.commit();
else
editor.abort();
}
snapshot = cache.get(key);
} else
Log.i(getTag(), "Snapshot found sending");
if (snapshot != null)
return (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
} catch (IOException e) {
e.printStackTrace();
}
Log.i(getTag(), "File stream is null");
return null;
}
public boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
HttpURLConnection urlConnection = null;
try {
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = urlConnection.getInputStream();
// you can use BufferedInputStream and BufferOuInputStream
IOUtils.copy(stream, outputStream);
IOUtils.closeQuietly(outputStream);
IOUtils.closeQuietly(stream);
Log.i(getTag(), "Stream closed all done");
return true;
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
IOUtils.close(urlConnection);
}
return false;
}
现在我的问题是如何从缓存中删除特定文件?在快照或lruCache的编辑器端是否缺少某些方法?预先感谢。