/** * 获取指定文件大小 * @param f * @return * @throws Exception */ public static long getFileSize(File file) throws Exception { long size = 0; if (file.exists()) { FileInputStream fis = null; fis = new FileInputStream(file); size = fis.available(); } else { file.createNewFile(); Log.e("获取文件大小", "文件不存在!"); } return size; }
/** * 获取指定文件夹 * @param f * @return * @throws Exception * */ public static long getFileSizes(File f) throws Exception { long size = 0; File flist[] = f.listFiles(); for (int i = 0; i < flist.length; i++) { if (flist[i].isDirectory()) { size = size + getFileSizes(flist[i]); } else { size = size + getFileSize(flist[i]); } } return size; }
/** * 转换文件大小 * @param fileS * @return * */ public static String FormetFileSize(long fileS) { DecimalFormat df = new DecimalFormat("#.00"); String fileSizeString = ""; String wrongSize = "0B"; if (fileS == 0) { return wrongSize; } 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) + "GB"; } return fileSizeString; }
时间: 2024-10-08 19:44:21