我需要使用合理的单位将文件大小显示为字符串。
例如,
1L ==> "1 B";
1024L ==> "1 KB";
2537253L ==> "2.3 MB"
等等
我找到了之前的答案,但我觉得不太满意。
我提出了自己的解决方案,但也有类似的缺点:
private static final long K = 1024;
private static final long M = K * K;
private static final long G = M * K;
private static final long T = G * K;
public static String convertToStringRepresentation(final long value){
final long[] dividers = new long[] { T, G, M, K, 1 };
final String[] units = new String[] { "TB", "GB", "MB", "KB", "B" };
if(value < 1)
throw new IllegalArgumentException("Invalid file size: " + value);
String result = null;
for(int i = 0; i < dividers.length; i++){
final long divider = dividers[i];
if(value >= divider){
result = format(value, divider, units[i]);
break;
}
}
return result;
}
private static String format(final long value,
final long divider,
final String unit){
final double result =
divider > 1 ? (double) value / (double) divider : (double) value;
return String.format("%.1f %s", Double.valueOf(result), unit);
}
主要问题是我对 Decimalformat 和/或 String.format 的了解有限。我希望 1024L、1025L 等映射到
1 KB
而不是 1.0 KB
。
所以,有两种可能性:
import java.text.DecimalFormat;
public static String readableFileSize(long size) {
if(size <= 0) return "0";
final String[] units = new String[] { "B", "kB", "MB", "GB", "TB", "PB", "EB" };
int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
这适用于所有输入(Long.MAX_VALUE 为 8 EB),并且程序很短!
有了
java.text.DecimalFormat
,你可能会更幸运。这段代码应该可以做到这一点(尽管只是即兴发挥......)
new DecimalFormat("#,##0.#").format(value) + " " + unit
令我惊讶的是,基于循环的算法大约快了 10%。
public static String toNumInUnits(long bytes) {
int u = 0;
for ( ; bytes > 1024*1024; bytes >>= 10) {
u++;
}
if (bytes > 1024)
u++;
return String.format("%.1f %cB", bytes/1024f, " kMGTPE".charAt(u));
}