1、获取文件夹大小:
1 /** 2 * 获取文件夹大小 3 * @param file File实例 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、删除文件夹下所有文件:
1 /** 2 * 删除指定目录下文件及目录 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()) {// 处理目录 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()) {// 如果是文件,删除 19 file.delete(); 20 } else {// 目录 21 if (file.listFiles().length == 0) {// 目录下没有文件或者目录,删除 22 file.delete(); 23 } 24 } 25 } 26 } catch (Exception e) { 27 // TODO Auto-generated catch block 28 e.printStackTrace(); 29 } 30 } 31 }
3、格式化文件夹大小单位:
1 /** 2 * 格式化单位 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 }
时间: 2024-10-10 08:33:57