根据文件大小自动转为以B,KB, MB, GB为单位的工具类.以后不用自己手动计算。
贴一下源代码,看了之后,让你感觉倍爽:
public static String formatFileSize(Context context, long number)
{
return formatFileSize(context, number, false);
}
public static String formatShortFileSize(Context context, long number)
{
return formatFileSize(context, number, true);
}
private static String formatFileSize(Context context, long number, boolean shorter)
{
if (context == null) {
return "";
}
float result = number;
int suffix = com.android.internal.R.string.byteShort;
if (result > 900) {
suffix = com.android.internal.R.string.kilobyteShort;
result = result / 1024;
}
if (result > 900) {
suffix = com.android.internal.R.string.megabyteShort;
result = result / 1024;
}
if (result > 900) {
suffix = com.android.internal.R.string.gigabyteShort;
result = result / 1024;
}
if (result > 900) {
suffix = com.android.internal.R.string.terabyteShort;
result = result / 1024;
}
if (result > 900) {
suffix = com.android.internal.R.string.petabyteShort;
result = result / 1024;
}
String value;
if (result < 1) {
value = String.format("%.2f", result);
} else if (result < 10) {
if (shorter) {
value = String.format("%.1f", result);
} else {
value = String.format("%.2f", result);
}
} else if (result < 100) {
if (shorter) {
value = String.format("%.0f", result);
} else {
value = String.format("%.2f", result);
}
} else {
value = String.format("%.0f", result);
}
return context.getResources().
getString(com.android.internal.R.string.fileSizeSuffix,
value, context.getString(suffix));
}
自己试试一下,看看效果。在子线程里面操作
new Thread() {
public void run() {
int i = 102;
do {
Log.e("tag", Formatter.formatFileSize(MainActivity.this, i));
Log.e("tag","short---"+ Formatter.formatShortFileSize(MainActivity.this, i));
i *= 1021;
} while (i > 0 && i < 1187708226);
};
}.start();
打印的结果如下:
以后计算文件大小就用它了!
当然自己实现方式也有:
/**
* 将byte转换为更加友好的单位
* @param sizeInB byte
* @return 更加友好的单位(KB、GB等)
*/
public static String readableStorageSize(long sizeInB) {
float floatSize = sizeInB;
int index = 0;
String[] units = new String[]{"B", "KB", "MB", "GB", "TB", "PB"};
while (floatSize > 1000 && index < 5) {
index++;
floatSize /= 1024;
}
String capacityText = new DecimalFormat("###,###,###.##").format(floatSize);
return String.format(Locale.ENGLISH, "%s%s", capacityText, units[index]);
}