Get readable folder size
//package cn.syncbox.client;
import java.io.File;
import java.net.HttpURLConnection;
import java.text.DecimalFormat;
import android.webkit.MimeTypeMap;
class Utils {
public static String[] formatSize(long bytes, int place) {
int level = 0;
float number = bytes;
String[] unit = { "bytes", "KB", "MB", "GB", "TB", "PB" };
while (number >= 1024f) {
number /= 1024f;
level++;
}
String formatStr = null;
if (place == 0) {
formatStr = "###0";
} else {
formatStr = "###0.";
for (int i = 0; i < place; i++) {
formatStr += "#";
}
}
DecimalFormat nf = new DecimalFormat(formatStr);
String[] value = new String[2];
value[0] = nf.format(number);
value[1] = unit[level];
return value;
}
public static long getFolderSize(File folderPath) {
long totalSize = 0;
if (folderPath == null) {
return 0;
}
if (!folderPath.isDirectory()) {
return 0;
}
File[] files = folderPath.listFiles();
for (File file : files) {
if (file.isFile()) {
totalSize += file.length();
} else if (file.isDirectory()) {
totalSize += file.length();
totalSize += getFolderSize(file);
}
}
return totalSize;
}
public static void clearFolder(File folderPath) {
if (folderPath == null) {
return;
}
if (!folderPath.isDirectory()) {
return;
}
File[] files = folderPath.listFiles();
for (File file : files) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
clearFolder(file);
file.delete();
}
}
}
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
// A file extension without the leading '.'
return uri.substring(dot).substring(1);
} else {
// No extension.
return "";
}
}
public static String getMimeType(String fullname) {
if (fullname == null) {
return null;
}
String type = HttpURLConnection.guessContentTypeFromName(fullname);
if (type == null) {
String ext = Utils.getExtension(fullname);
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
}
// default
if (type == null) {
type = "application/octet-stream";
}
return type;
}
}
Related examples in the same category