读取文件夹大小
String fileSizeStr = FileHelper.getFileSize(f);
看看FileHelper中的getFileSize怎么实现:
// 返回文件大小字符串
public static String getFileSize(File file) {
double size = getFileLength(file);
return sizeToString(size);
}
这里有两个方法getFileLength()和sizeToString()
// 递归遍历每个文件的大小
public static long getFileLength(File file) {
if (file == null)
return -1;
long size = 0;
if (!file.isDirectory()) {
size = file.length();
} else {
for (File f : listFiles(file)) {
size += getFileLength(f);
}
}
return size;
}
// 把文件大小转化成容易理解的格式显示,如多少M
public static String sizeToString(double size) {
String str = "";
if (size >= 0 && size < ONE_KB_SIZE) {
str = Integer.toString((int) size) + BT_TAG;
} else if (size >= ONE_KB_SIZE && size < ONE_MB_SIZE) {
str = String.format("%.2f", size / ONE_KB_SIZE) + KB_TAG;
} else if (size >= ONE_MB_SIZE && size < ONE_GB_SIZE) {
str = String.format("%.2f", size / ONE_MB_SIZE) + MB_TAG;
} else {
str = String.format("%.2f", size / ONE_GB_SIZE) + GB_TAG;
}
return str;
}
网友评论