返回

[每日分享]android获取文件目录总大小实现清除缓存

发布时间:2022-11-30 04:05:48 394
# 数据

跟大家讲一个笑话,我维护老项目,看到有一个清除缓存功能,我看了一下怎么实现的,结果就一个​​Toast​​太逗比了

/**
* 获取指定文件夹的大小
*
* @param f
* @return
* @throws Exception
*/
public static long getFileSizes(File f) {
long size = 0;
File flist[] = f.listFiles();//文件夹目录下的所有文件
if (flist == null) {//4.2的模拟器空指针。
return 0;
}
if (flist != null) {
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {//判断是否父目录下还有子目录
size = size + getFileSizes(flist[i]);
} else {
size = size + getFileSize(flist[i]);
}
}
}
return size;
}

获取文件大小

}

/**
* 获取指定文件的大小
*
* @return
* @throws Exception
*/
public static long getFileSize(File file) {

long size = 0;
if (file.exists()) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);//使用FileInputStream读入file的数据流
size = fis.available();//文件的大小
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}

} else {
}
return size;
}

计算当前应用缓存文件夹

File file1 = AppContext.getInstance().getCacheDir();
File file2 = AppContext.getInstance().getExternalCacheDir();
long fileSizes = FileUtils.getFileSizes(file1);
long fileSizes2 = FileUtils.getFileSizes(file2);
return fileSizes + fileSizes2;

清除所有缓存

public static boolean clearAllCache() {
File externalCacheDir = SuperAppContext.getInstance().getExternalCacheDir();
File cacheDir = SuperAppContext.getInstance().getCacheDir();
boolean result = false;
if (cacheDir != null) {
result = delAllFile(cacheDir.getAbsolutePath());
}
if (externalCacheDir != null) {

result = delAllFile(externalCacheDir.getAbsolutePath()) || result ? true : false;//原生是真 或者现在是true就是true
}
return result;
}

删除文件夹

//删除指定文件夹下所有文件
//param path 文件夹完整绝对路径
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]);//再删除空文件夹
flag = true;
}
}
return flag;
}

删除volley, uiversalCache文件夹

public static File getVolleyCacheFile() {
return productSystemCacheFolder("volley");
}

public static File getImageUniversalCacheFile() {
return productSystemCacheFolder("uil-images");
}
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线