[Android Notes] Android calculates the folder size, deletes all files in the folder, and android notes
1. Get the folder size:
1/** 2 * Get the folder size 3 * @ param file File instance 4 * @ return long 5 */6 public static long getFolderSize (java. io. file file) {7 8 long size = 0; 9 try {10 java. io. file [] fileList = file. listFiles (); 11 for (int I = 0; I <fileList. length; I ++) 12 {13 if (fileList [I]. isDirectory () 14 {15 size = size + getFolderSize (fileList [I]); 16 17} else {18 size = size + fileList [I]. length (); 19 20} 21} 22} catch (Exception e) {23 // TODO Auto-generated catch block 24 e. printStackTrace (); 25} 26 // return size/1048576; 27 return size; 28}
2. Delete all files in the folder:
1/** 2 * Delete files and directories in the specified directory 3 * @ param deleteThisPath 4 * @ param filepath 5 * @ return 6 */7 public void deleteFolderFile (String filePath, boolean deleteThisPath) {8 if (! TextUtils. isEmpty (filePath) {9 try {10 File file = new File (filePath); 11 if (file. isDirectory () {// processing Directory 12 File files [] = file. listFiles (); 13 for (int I = 0; I <files. length; I ++) {14 deleteFolderFile (files [I]. getAbsolutePath (), true); 15} 16} 17 if (deleteThisPath) {18 if (! File. isDirectory () {// if it is a file, delete 19 files. delete (); 20} else {// directory 21 if (file. listFiles (). length = 0) {// The directory contains no files or directories. Delete 22 files. delete (); 23} 24} 25} 26} catch (Exception e) {27 // TODO Auto-generated catch block 28 e. printStackTrace (); 29} 30} 31}
3. format the folder size unit:
1/** 2 * formatting Unit 3 * @ param size 4 * @ return 5 */6 public static String getFormatSize (double size) {7 double kiloByte = size/1024; 8 if (kiloByte <1) {9 return size + "B"; 10} 11 12 double megaByte = kiloByte/1024; 13 if (megaByte <1) {14 BigDecimal result1 = new BigDecimal (Double. toString (kiloByte); 15 return result1.setScale (2, BigDecimal. ROUND_HALF_UP ). toPlainString () + "KB"; 16} 17 18 double gigaByte = megaByte/1024; 19 if (gigaByte <1) {20 BigDecimal result2 = new BigDecimal (Double. toString (megaByte); 21 return result2.setScale (2, BigDecimal. ROUND_HALF_UP ). toPlainString () + "MB"; 22} 23 24 double teraBytes = gigaByte/1024; 25 if (teraBytes <1) {26 BigDecimal result3 = new BigDecimal (Double. toString (gigaByte); 27 return result3.setScale (2, BigDecimal. ROUND_HALF_UP ). toPlainString () + "GB"; 28} 29 BigDecimal result4 = new BigDecimal (teraBytes); 30 return result4.setScale (2, BigDecimal. ROUND_HALF_UP ). toPlainString () + "TB"; 31}