/** * 获取指定文件夹下,文件的大小 * * @param file * @return */ public static long getFileSizes(File file) { long size = 0; if (file == null) { return size; } File fList[] = file.listFiles(); if (fList == null) { return size; } for (int i = 0; i < fList.length; i++) { if (fList[i].isDirectory()) { size += getFileSizes(fList[i]); } else { size += getFileSize(fList[i]); } } return size; } /** * 获取指定文件夹下,以suffix为后缀文件的大小 * * @param file * @param suffix * @return */ public static long getFileSizes(File file, String suffix) { long size = 0; if (file == null) { return size; } File fList[] = file.listFiles(); if (fList == null) { return size; } for (int i = 0; i < fList.length; i++) { if (fList[i].isDirectory()) { size += getFileSizes(fList[i], suffix); } else { String fileName = fList[i].getName(); String prefix = fileName.substring(fileName.lastIndexOf(".") + 1); if (!TextUtils.isEmpty(prefix) && prefix.contains(suffix)) { size += getFileSize(fList[i]); } } } return size; } /** * 获取指定文件的大小 * * @param file * @return */ public static long getFileSize(File file) { long size = 0; if (file == null || !file.exists()) { return size; } try { FileInputStream fileInputStream = new FileInputStream(file); size = fileInputStream.available(); } catch (IOException e) { e.printStackTrace(); } return size; } /** * 格式化单位 * * @param size * @return */ public static String getFormatSize(double size) { double kiloByte = size / 1024; 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"; }
获取指定文件夹下,文件的大小,及单位换算
最新推荐文章于 2024-04-27 18:21:53 发布