本文介紹了將文件大小格式化為 MB、GB 等的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我需要使用合理的單位將文件大小顯示為字符串.
例如,
等等
我發(fā)現(xiàn) this previous answer,我覺(jué)得不滿意.
我想出了自己的解決方案,但也有類似的缺點(diǎn):
主要問(wèn)題是我對(duì) Decimalformat 和/或 String.format 的了解有限.我希望 1024L、1025L 等映射到 1 KB 而不是 1.0 KB.
所以,有兩種可能:
我更喜歡公共圖書(shū)館中的開(kāi)箱即用解決方案,例如 Apache Commons 或 Google Guava.
如果沒(méi)有,我怎樣才能擺脫 '.0' 部分(不求助于字符串替換和正則表達(dá)式,我可以自己做)?
解決方案
這將工作到 1000 TB....而且程序很短!
I need to display a file size as a string using sensible units.
For example,1L ==> "1 B";
1024L ==> "1 KB";
2537253L ==> "2.3 MB"
etc.
I found this previous answer, which I didn't find satisfactory.
I have come up with my own solution which has similar shortcomings: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);
}
The main problem is my limited knowledge of Decimalformat and / or String.format. I would like 1024L, 1025L, etc. to map to 1 KB rather than 1.0 KB.
So, two possibilities:
I would prefer a good out-of-the-box solution in a public library like Apache Commons or Google Guava.
If there isn't, how can I get rid of the '.0' part (without resorting to string replacement and regex, I can do that myself)?
解決方案 public static String readableFileSize(long size) {
if(size <= 0) return "0";
final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" };
int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
This will work up to 1000 TB.... and the program is short!
這篇關(guān)于將文件大小格式化為 MB、GB 等的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!