public class CacheManager {
private static final long MAX_SIZE = 5242880L; // 5MB
private CacheManager() {
}
public static void cacheData(Context context, byte[] data, String name) throws IOException {
File cacheDir = context.getCacheDir();
long size = getDirSize(cacheDir);
long newSize = data.length + size;
if (newSize > MAX_SIZE) {
cleanDir(cacheDir, newSize - MAX_SIZE);
}
File file = new File(cacheDir, name);
FileOutputStream os = new FileOutputStream(file);
try {
os.write(data);
}
finally {
os.flush();
os.close();
}
}
public static byte[] retrieveData(Context context, String name) throws IOException {
File cacheDir = context.getCacheDir();
File file = new File(cacheDir, name);
if (!file.exists()) {
// Data doesn't exist
return null;
}
byte[] data = new byte[(int) file.length()];
FileInputStream is = new FileInputStream(file);
try {
is.read(data);
}
finally {
is.close();
}
return data;
}
private static void cleanDir(File dir, long bytes) {
long bytesDeleted = 0;
File[] files = dir.listFiles();
for (File file : files) {
bytesDeleted += file.length();
file.delete();
if (bytesDeleted >= bytes) {
break;
}
}
}
private static long getDirSize(File dir) {
long size = 0;
File[] files = dir.listFiles();
for (File file : files) {
if (file.isFile()) {
size += file.length();
}
}
return size;
}
}
使用緩存問題
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
Basic Android Interview Questions
letstalktech88
2021-06-01 18:54:25
聚焦市场开发热门技术 手把手带你开发商业级社交App
wy53780
2020-04-23 14:07:47
逆向美团外卖app__skcy算法
1939481097
2019-12-11 11:33:48
逆向淘宝x-sign算法
1939481097
2019-12-11 11:30:02
Android 原生app獲取用戶授權訪問Autodesk雲應用數據
樑曉冬
2019-02-24 23:44:12
Android平臺調用WebService詳解
推薦碼發放
2019-02-24 19:41:33
Android開發學習之使用Toolbar實現不同的Fragment使用不同顏色的標題欄與狀態欄
優惠券發放
2019-02-24 19:41:23
虹軟人臉識別ArcFace2.0 Android SDK使用教程
gsmd_cc
2019-02-24 19:04:27
爲什麼要做短視頻秒播優化
WalkerXu
2019-02-24 15:34:05
Android Architecture Components——Room
大熊啊啊啊
2019-02-24 14:08:54
Android高效安全加載圖片的方法詳解
我爱宋慧乔
2019-02-24 12:42:54
第二十二章:動畫(四)
wangccsy
2019-02-24 10:57:10
android入門系列
尋夢緣2008
2019-02-23 13:56:52