Android 如何统计Glide缓存文件大小?
2023-08-28 本文已影响0人
buhanzhe
问了下GPT 哈哈困扰已久的问题解决了!GPT真懂呀。。。
以下代码是统计当日下载的glide缓存。仅供参考!
public static double getGlideTodaySize(Context context) {
// 获取 Glide 缓存目录
File cacheDir = Glide.getPhotoCacheDir(context);
return getTodaySize(cacheDir, context);
}
private static double getTodaySize(File cacheDir, Context context) {
// 获取缓存目录下的所有文件
List<File> cacheFiles = getAllFiles(cacheDir);
// 记录当天的缓存增量
long cacheIncrement = 0;
// 获取当天的日期
Calendar today = Calendar.getInstance();
int currentYear = today.get(Calendar.YEAR);
int currentMonth = today.get(Calendar.MONTH);
int currentDay = today.get(Calendar.DAY_OF_MONTH);
// 遍历所有缓存文件
for (File file : cacheFiles) {
// 获取文件最后修改时间
long lastModified = file.lastModified();
Calendar modifiedDate = Calendar.getInstance();
modifiedDate.setTimeInMillis(lastModified);
// 检查文件是否是当天的缓存
int modifiedYear = modifiedDate.get(Calendar.YEAR);
int modifiedMonth = modifiedDate.get(Calendar.MONTH);
int modifiedDay = modifiedDate.get(Calendar.DAY_OF_MONTH);
if (modifiedYear == currentYear && modifiedMonth == currentMonth && modifiedDay == currentDay) {
// 累计当天的缓存增量
cacheIncrement += file.length();
}
}
return cacheIncrement / Math.pow(2, 20);
}
public static List<File> getAllFiles(File folder) {
List<File> fileList = new ArrayList<>();
if (folder.exists() && folder.isDirectory()) {
File[] files = folder.listFiles();
if (files != null && files.length > 0) {
for (File file : files) {
if (file.isFile()) {
fileList.add(file);
} else if (file.isDirectory()) {
fileList.addAll(getAllFiles(file));
}
}
}
}
return fileList;
}