跟大家讲一个笑话,我维护老项目,看到有一个清除缓存功能,我看了一下怎么实现的,结果就一个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,file,文件夹,File,path,文件目录,android,size From: https://blog.51cto.com/u_15458814/5882981
return productSystemCacheFolder("volley");
}
public static File getImageUniversalCacheFile() {
return productSystemCacheFolder("uil-images");
}