如何在Java中将字节大小转换为人类可读的格式? 像1024应该变成“ 1 Kb”,而1024 * 1024应该变成“ 1 Mb”。
我有点讨厌为每个项目编写此实用程序方法。 Apache Commons中是否有任何静态方法呢?
#1楼
filename=filedilg.getSelectedFile().getAbsolutePath();
File file=new File(filename);
String disp=FileUtils.byteCountToDisplaySize(file.length());
System.out.println("THE FILE PATH IS "+file+"THIS File SIZE IS IN MB "+disp);
#2楼
public static String floatForm (double d)
{
return new DecimalFormat("#.##").format(d);
}
public static String bytesToHuman (long size)
{
long Kb = 1 * 1024;
long Mb = Kb * 1024;
long Gb = Mb * 1024;
long Tb = Gb * 1024;
long Pb = Tb * 1024;
long Eb = Pb * 1024;
if (size < Kb) return floatForm( size ) + " byte";
if (size >= Kb && size < Mb) return floatForm((double)size / Kb) + " Kb";
if (size >= Mb && size < Gb) return floatForm((double)size / Mb) + " Mb";
if (size >= Gb && size < Tb) return floatForm((double)size / Gb) + " Gb";
if (size >= Tb && size < Pb) return floatForm((double)size / Tb) + " Tb";
if (size >= Pb && size < Eb) return floatForm((double)size / Pb) + " Pb";
if (size >= Eb) return floatForm((double)size / Eb) + " Eb";
return "???";
}
#3楼
替代方案,这是基于此热门帖子的解决方案:
/**
* formats the bytes to a human readable format
*
* @param si true if each kilo==1000, false if kilo==1024
*/
@SuppressLint("DefaultLocale")
public static String humanReadableByteCount(final long bytes,final boolean si)
{
final int unit=si ? 1000 : 1024;
if(bytes
return bytes+" B";
double result=bytes;
final String unitsToUse=(si ? "k" : "K")+"MGTPE";
int i=0;
final int unitsCount=unitsToUse.length();
while(true)
{
result/=unit;
if(result
break;
// check if we can go further:
if(i==unitsCount-1)
break;
++i;
}
final StringBuilder sb=new StringBuilder(9);
sb.append(String.format("%.1f ",result));
sb.append(unitsToUse.charAt(i));
if(si)
sb.append('B');
else sb.append('i').append('B');
final String resultStr=sb.toString();
return resultStr;
}
#4楼
我们可以完全避免使用缓慢的Math.pow()和Math.log()方法而不牺牲简单性,因为单元之间的因子(例如B,KB,MB等)为1024,即2 ^ 10。 Long类有一个方便的numberOfLeadingZeros()方法,我们可以使用该方法判断大小值属于哪个单位。
关键点:大小单位之间的距离为10位(1024 = 2 ^ 10),表示最高1位的位置-换句话说,前导零的数量相差10(字节= KB * 1024,KB = MB * 1024等)。
前导零的数量与大小单位之间的相关性:
# of leading 0's Size unit
-------------------------------
>53 B (Bytes)
>43 KB
>33 MB
>23 GB
>13 TB
>3 PB
<=2 EB
最终代码:
public static String formatSize(long v) {
if (v < 1024) return v + " B";
int z = (63 - Long.numberOfLeadingZeros(v)) / 10;
return String.format("%.1f %sB", (double)v / (1L << (z*10)), " KMGTPE".charAt(z));
}
#5楼
使用Android内置类
对于Android,有一个Formatter类。 就像代码一样,您就完成了。
android.text.format.Formatter.formatShortFileSize(activityContext, bytes);
就像formatFileSize() ,但是尝试生成更短的数字(显示更少的小数)。
android.text.format.Formatter.formatFileSize(activityContext, bytes);
将内容大小格式化为字节,千字节,兆字节等形式。