本地文件缓存工具类

public class CacheUtil {

/**
* 获取文件缓存数据的大小
*/
public static String getFileCacheSize(String imagePath,String soundPath) {
float cacheSize = 0;
String cacheSizeStr = "";
File imageFile = new File(imagePath);
File soundFile = new File(soundPath);
File[] imageF;
File[] soundF;
if (imageFile.exists()) {
imageF = imageFile.listFiles();

for (int i = 0; i < imageF.length; i++) {
cacheSize += imageF[i].length();
}
}
if (soundFile.exists()) {
soundF = soundFile.listFiles();

for (int i = 0; i < soundF.length; i++) {
cacheSize += soundF[i].length();
}
}
cacheSize = cacheSize / 1024 / 1024;
DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
cacheSizeStr = decimalFormat.format(cacheSize);//format 返回的是字符串
return cacheSizeStr;
}

/**
* 清空文件缓存
*/
public static void clearFileCache(String imagePath,String soundPath){
File imageFile = new File(imagePath);
File soundFile = new File(soundPath);
File[] imageF = imageFile.listFiles();
File[] soundF = soundFile.listFiles();
if (imageFile.exists()) {
for (int i = 0; i < imageF.length; i++) {
clear(imageF[i]);
}
}
if (soundFile.exists()) {
for (int i = 0; i < soundF.length; i++) {
clear(soundF[i]);
}
}
}

/**
* 若将整个ttpod文件夹删除,则只需调用这个方法
*/
public static void clear(File file) {
if (file.exists()) { //指定文件是否存在
if (file.isFile()) { //该路径名表示的文件是否是一个标准文件
file.delete(); //删除该文件
} else if (file.isDirectory()) { //该路径名表示的文件是否是一个目录(文件夹)
File[] files = file.listFiles(); //列出当前文件夹下的所有文件
for (File f : files) {
clear(f); //递归删除
}
}
file.delete(); //删除文件夹(song,art,lyric)
}
}
}
posted @ 2016-10-19 10:24  黑色秋梨膏  阅读(158)  评论(0编辑  收藏  举报