如何在Java中将字节大小转换为人类可读的格式?
比如1024应该变成“1 Kb”,1024*1024应该变成“1 Mb”。
我有点厌倦了为每个项目写这个实用方法。在Apache Commons中有这样的静态方法吗?
如何在Java中将字节大小转换为人类可读的格式?
比如1024应该变成“1 Kb”,1024*1024应该变成“1 Mb”。
我有点厌倦了为每个项目写这个实用方法。在Apache Commons中有这样的静态方法吗?
当前回答
使用下面的函数来获得确切的信息。它是基于atm_cashwithdraw概念生成的。
getFullMemoryUnit(): Total: [123 MB], Max: [1 GB, 773 MB, 512 KB], Free: [120 MB, 409 KB, 304 Bytes]
public static String getFullMemoryUnit(long unit) {
long BYTE = 1024, KB = BYTE, MB = KB * KB, GB = MB * KB, TB = GB * KB;
long KILO_BYTE, MEGA_BYTE = 0, GIGA_BYTE = 0, TERA_BYTE = 0;
unit = Math.abs(unit);
StringBuffer buffer = new StringBuffer();
if ( unit / TB > 0 ) {
TERA_BYTE = (int) (unit / TB);
buffer.append(TERA_BYTE+" TB");
unit -= TERA_BYTE * TB;
}
if ( unit / GB > 0 ) {
GIGA_BYTE = (int) (unit / GB);
if (TERA_BYTE != 0) buffer.append(", ");
buffer.append(GIGA_BYTE+" GB");
unit %= GB;
}
if ( unit / MB > 0 ) {
MEGA_BYTE = (int) (unit / MB);
if (GIGA_BYTE != 0) buffer.append(", ");
buffer.append(MEGA_BYTE+" MB");
unit %= MB;
}
if ( unit / KB > 0 ) {
KILO_BYTE = (int) (unit / KB);
if (MEGA_BYTE != 0) buffer.append(", ");
buffer.append(KILO_BYTE+" KB");
unit %= KB;
}
if ( unit > 0 ) buffer.append(", "+unit+" Bytes");
return buffer.toString();
}
我刚刚修改了facebookarchive-StringUtils的代码以获得以下格式。与使用apache.hadoop-StringUtils时得到的格式相同
getMemoryUnit(): Total: [123.0 MB], Max: [1.8 GB], Free: [120.4 MB]
public static String getMemoryUnit(long bytes) {
DecimalFormat oneDecimal = new DecimalFormat("0.0");
float BYTE = 1024.0f, KB = BYTE, MB = KB * KB, GB = MB * KB, TB = GB * KB;
long absNumber = Math.abs(bytes);
double result = bytes;
String suffix = " Bytes";
if (absNumber < MB) {
result = bytes / KB;
suffix = " KB";
} else if (absNumber < GB) {
result = bytes / MB;
suffix = " MB";
} else if (absNumber < TB) {
result = bytes / GB;
suffix = " GB";
}
return oneDecimal.format(result) + suffix;
}
以上方法的使用示例:
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
int availableProcessors = runtime.availableProcessors();
long heapSize = Runtime.getRuntime().totalMemory();
long heapMaxSize = Runtime.getRuntime().maxMemory();
long heapFreeSize = Runtime.getRuntime().freeMemory();
System.out.format("Total: [%s], Max: [%s], Free: [%s]\n", heapSize, heapMaxSize, heapFreeSize);
System.out.format("getMemoryUnit(): Total: [%s], Max: [%s], Free: [%s]\n",
getMemoryUnit(heapSize), getMemoryUnit(heapMaxSize), getMemoryUnit(heapFreeSize));
System.out.format("getFullMemoryUnit(): Total: [%s], Max: [%s], Free: [%s]\n",
getFullMemoryUnit(heapSize), getFullMemoryUnit(heapMaxSize), getFullMemoryUnit(heapFreeSize));
}
字节来获取上面的格式
Total: [128974848], Max: [1884815360], Free: [126248240]
为了以人类可读的格式显示时间,请使用函数millisToShortDHMS(长持续时间)。
其他回答
我最近问了同样的问题:
格式文件大小为MB, GB等。
虽然没有开箱即用的答案,但我可以接受这个解决方案:
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 new DecimalFormat("#,##0.#").format(result) + " " + unit;
}
测试代码:
public static void main(final String[] args){
final long[] l = new long[] { 1l, 4343l, 43434334l, 3563543743l };
for(final long ll : l){
System.out.println(convertToStringRepresentation(ll));
}
}
输出(在我的德语地区):
1 B
4,2 KB
41,4 MB
3,3 GB
我已经打开了一个问题,要求谷歌番石榴的这个功能。也许有人愿意支持它。
private static final String[] Q = new String[]{"", "K", "M", "G", "T", "P", "E"};
public String getAsString(long bytes)
{
for (int i = 6; i > 0; i--)
{
double step = Math.pow(1024, i);
if (bytes > step) return String.format("%3.1f %s", bytes / step, Q[i]);
}
return Long.toString(bytes);
}
使用下面的函数来获得确切的信息。它是基于atm_cashwithdraw概念生成的。
getFullMemoryUnit(): Total: [123 MB], Max: [1 GB, 773 MB, 512 KB], Free: [120 MB, 409 KB, 304 Bytes]
public static String getFullMemoryUnit(long unit) {
long BYTE = 1024, KB = BYTE, MB = KB * KB, GB = MB * KB, TB = GB * KB;
long KILO_BYTE, MEGA_BYTE = 0, GIGA_BYTE = 0, TERA_BYTE = 0;
unit = Math.abs(unit);
StringBuffer buffer = new StringBuffer();
if ( unit / TB > 0 ) {
TERA_BYTE = (int) (unit / TB);
buffer.append(TERA_BYTE+" TB");
unit -= TERA_BYTE * TB;
}
if ( unit / GB > 0 ) {
GIGA_BYTE = (int) (unit / GB);
if (TERA_BYTE != 0) buffer.append(", ");
buffer.append(GIGA_BYTE+" GB");
unit %= GB;
}
if ( unit / MB > 0 ) {
MEGA_BYTE = (int) (unit / MB);
if (GIGA_BYTE != 0) buffer.append(", ");
buffer.append(MEGA_BYTE+" MB");
unit %= MB;
}
if ( unit / KB > 0 ) {
KILO_BYTE = (int) (unit / KB);
if (MEGA_BYTE != 0) buffer.append(", ");
buffer.append(KILO_BYTE+" KB");
unit %= KB;
}
if ( unit > 0 ) buffer.append(", "+unit+" Bytes");
return buffer.toString();
}
我刚刚修改了facebookarchive-StringUtils的代码以获得以下格式。与使用apache.hadoop-StringUtils时得到的格式相同
getMemoryUnit(): Total: [123.0 MB], Max: [1.8 GB], Free: [120.4 MB]
public static String getMemoryUnit(long bytes) {
DecimalFormat oneDecimal = new DecimalFormat("0.0");
float BYTE = 1024.0f, KB = BYTE, MB = KB * KB, GB = MB * KB, TB = GB * KB;
long absNumber = Math.abs(bytes);
double result = bytes;
String suffix = " Bytes";
if (absNumber < MB) {
result = bytes / KB;
suffix = " KB";
} else if (absNumber < GB) {
result = bytes / MB;
suffix = " MB";
} else if (absNumber < TB) {
result = bytes / GB;
suffix = " GB";
}
return oneDecimal.format(result) + suffix;
}
以上方法的使用示例:
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
int availableProcessors = runtime.availableProcessors();
long heapSize = Runtime.getRuntime().totalMemory();
long heapMaxSize = Runtime.getRuntime().maxMemory();
long heapFreeSize = Runtime.getRuntime().freeMemory();
System.out.format("Total: [%s], Max: [%s], Free: [%s]\n", heapSize, heapMaxSize, heapFreeSize);
System.out.format("getMemoryUnit(): Total: [%s], Max: [%s], Free: [%s]\n",
getMemoryUnit(heapSize), getMemoryUnit(heapMaxSize), getMemoryUnit(heapFreeSize));
System.out.format("getFullMemoryUnit(): Total: [%s], Max: [%s], Free: [%s]\n",
getFullMemoryUnit(heapSize), getFullMemoryUnit(heapMaxSize), getFullMemoryUnit(heapFreeSize));
}
字节来获取上面的格式
Total: [128974848], Max: [1884815360], Free: [126248240]
为了以人类可读的格式显示时间,请使用函数millisToShortDHMS(长持续时间)。
如果在Android上,你可以简单地调用Android .text. format . formatter的一个静态方法。
https://developer.android.com/reference/android/text/format/Formatter
我们可以完全避免使用缓慢的Math.pow()和Math.log()方法,而不会牺牲简单性,因为单位之间的因子(例如,B, KB, MB等)是1024,即2^10。Long类有一个方便的numberofleadingzero()方法,我们可以用它来告诉大小值落在哪个单元中。
重点:大小单位的距离为10位(1024 = 2^10),这意味着最高位的位置-换句话说,前导零的数量-相差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 |
<=3 | 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));
}