android 統計資料夾大小及刪除資料夾下所有檔案和路徑
yangxi_001發表於2014-11-28
-
-
-
-
-
-
public static long getFolderSize(java.io.File file){
-
-
long size = 0;
-
try {
-
java.io.File[] fileList = file.listFiles();
-
for (int i = 0; i < fileList.length; i++)
-
{
-
if (fileList[i].isDirectory())
-
{
-
size = size + getFolderSize(fileList[i]);
-
-
}else{
-
size = size + fileList[i].length();
-
-
}
-
}
-
} catch (Exception e) {
-
-
e.printStackTrace();
-
}
-
-
return size;
-
}
-
-
-
-
-
-
-
-
public void deleteFolderFile(String filePath, boolean deleteThisPath) {
-
if (!TextUtils.isEmpty(filePath)) {
-
try {
-
File file = new File(filePath);
-
if (file.isDirectory()) {
-
File files[] = file.listFiles();
-
for (int i = 0; i < files.length; i++) {
-
deleteFolderFile(files[i].getAbsolutePath(), true);
-
}
-
}
-
if (deleteThisPath) {
-
if (!file.isDirectory()) {
-
file.delete();
-
} else {
-
if (file.listFiles().length == 0) {
-
file.delete();
-
}
-
}
-
}
-
} catch (Exception e) {
-
-
e.printStackTrace();
-
}
-
}
-
}
-
-
-
-
-
-
public static String getFormatSize(double size) {
-
double kiloByte = size/1024;
-
if(kiloByte < 1) {
-
return size + "Byte(s)";
-
}
-
-
double megaByte = kiloByte/1024;
-
if(megaByte < 1) {
-
BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
-
return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
-
}
-
-
double gigaByte = megaByte/1024;
-
if(gigaByte < 1) {
-
BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
-
return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
-
}
-
-
double teraBytes = gigaByte/1024;
-
if(teraBytes < 1) {
-
BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
-
return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
-
}
-
BigDecimal result4 = new BigDecimal(teraBytes);
-
return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
-
}