Skip to content

Instantly share code, notes, and snippets.

@vuhung3990
Created October 3, 2014 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vuhung3990/19689416b1873c6ddfaf to your computer and use it in GitHub Desktop.
Save vuhung3990/19689416b1873c6ddfaf to your computer and use it in GitHub Desktop.
PERMISSION: READ_EXTERNAL , WRITE_EXTERNAL
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[0]+" "+value[1];
}
public static long getFolderSize(File folderPath) {
long totalSize = 0;
if (folderPath == null) {
return 0;
}
if (!folderPath.isDirectory()) {
return folderPath.length();
}
try {
File[] files = folderPath.listFiles();
for (File file : files) {
if (file.isFile()) {
totalSize += file.length();
} else if (file.isDirectory()) {
totalSize += file.length();
totalSize += getFolderSize(file);
}
}
} catch (Exception e) {
e.printStackTrace();
}
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();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment