//这只是一个工具类,在点击清楚缓存时,调用这个工具类就行
public class ClearFileUtils {
public long len=0;
/**
* 要修改的TextView
* @param v
* @param context
* @param file
*/
public void clearFile(final TextView v, Context context, final File file){
AlertDialog dialog=new AlertDialog.Builder(context)
.setTitle("是否删除")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
clear(file);
v.setText("0");
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).show();
}
public void clear(File file)
{
//判断是否为文件
if(file.isFile())
{
file.delete();
}
else
{
if(file!=null)
{
File[] files = file.listFiles();
for (File f : files) {
if(f.isFile())
{
f.delete();
}
else
{
gain(f);
}
}
}
}
}
/**
* 获得文件大小
* @param file
* @return
*/
public String gainFileSize(final File file){
String length="";
long clear = gain(file);
//转化
length = formatFileSize(clear);
return length;
}
public long gain(File file)
{
//判断是否为文件
if(file.isFile())
{
len+= file.length();
}
else
{
if(file!=null)
{
File[] files = file.listFiles();
for (File f : files) {
if(f.isFile())
{
len+=f.length();
}
else
{
gain(f);
}
}
}
}
return len;
}
/**
* 转化文件大小为k,b,m,GB
* @param fileS
* @return
*/
public static String formatFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");//保留两位小数
String fileSizeString = "";
if(fileS!=0) {
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "MB";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "G";
}
}
else
{
fileSizeString="0";
}
return fileSizeString;
}
}