使用缓存问题

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;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值