如何在Java中将字节大小转换为人类可读的格式?
比如1024应该变成“1 Kb”,1024*1024应该变成“1 Mb”。
我有点厌倦了为每个项目写这个实用方法。在Apache Commons中有这样的静态方法吗?
如何在Java中将字节大小转换为人类可读的格式?
比如1024应该变成“1 Kb”,1024*1024应该变成“1 Mb”。
我有点厌倦了为每个项目写这个实用方法。在Apache Commons中有这样的静态方法吗?
当前回答
Kotlin爱好者可以使用这个扩展:
fun Long.readableFormat(): String {
if (this <= 0 ) return "0"
val units = arrayOf("B", "kB", "MB", "GB", "TB")
val digitGroups = (log10(this.toDouble()) / log10(1024.0)).toInt()
return DecimalFormat("#,##0.#").format(this / 1024.0.pow(digitGroups.toDouble())).toString() + " " + units[digitGroups]
}
现在使用
val size : Long = 90836457
val readbleString = size.readableFormat()
另一种方法
val Long.formatSize : String
get() {
if (this <= 0) return "0"
val units = arrayOf("B", "kB", "MB", "GB", "TB")
val digitGroups = (log10(this.toDouble()) / log10(1024.0)).toInt()
return DecimalFormat("#,##0.#").format(this / 1024.0.pow(digitGroups.toDouble())).toString() + " " + units[digitGroups]
}
现在使用
val size : Long = 90836457
val readbleString = size.formatSize
其他回答
private String bytesIntoHumanReadable(long bytes) {
long kilobyte = 1024;
long megabyte = kilobyte * 1024;
long gigabyte = megabyte * 1024;
long terabyte = gigabyte * 1024;
if ((bytes >= 0) && (bytes < kilobyte)) {
return bytes + " B";
} else if ((bytes >= kilobyte) && (bytes < megabyte)) {
return (bytes / kilobyte) + " KB";
} else if ((bytes >= megabyte) && (bytes < gigabyte)) {
return (bytes / megabyte) + " MB";
} else if ((bytes >= gigabyte) && (bytes < terabyte)) {
return (bytes / gigabyte) + " GB";
} else if (bytes >= terabyte) {
return (bytes / terabyte) + " TB";
} else {
return bytes + " Bytes";
}
}
Kotlin版本通过扩展属性
如果您正在使用Kotlin,那么通过这些扩展名属性格式化文件大小非常容易。它是无循环的,完全基于纯数学。
HumanizeUtils.kt
import java.io.File
import kotlin.math.log2
import kotlin.math.pow
/**
* @author aminography
*/
val File.formatSize: String
get() = length().formatAsFileSize
val Int.formatAsFileSize: String
get() = toLong().formatAsFileSize
val Long.formatAsFileSize: String
get() = log2(if (this != 0L) toDouble() else 1.0).toInt().div(10).let {
val precision = when (it) {
0 -> 0; 1 -> 1; else -> 2
}
val prefix = arrayOf("", "K", "M", "G", "T", "P", "E", "Z", "Y")
String.format("%.${precision}f ${prefix[it]}B", toDouble() / 2.0.pow(it * 10.0))
}
用法:
println("0: " + 0.formatAsFileSize)
println("170: " + 170.formatAsFileSize)
println("14356: " + 14356.formatAsFileSize)
println("968542985: " + 968542985.formatAsFileSize)
println("8729842496: " + 8729842496.formatAsFileSize)
println("file: " + file.formatSize)
结果:
0: 0 B
170: 170 B
14356: 14.0 KB
968542985: 923.67 MB
8729842496: 8.13 GB
file: 6.15 MB
现在有一个包含单元格式的库可用。我把它添加到triava库,因为唯一的其他现有库似乎是Android的。
它可以格式化数字与任意精度,在3个不同的系统(SI, IEC, JEDEC)和各种输出选项。下面是来自triava单元测试的一些代码示例:
UnitFormatter.formatAsUnit(1126, UnitSystem.SI, "B");
// = "1.13kB"
UnitFormatter.formatAsUnit(2094, UnitSystem.IEC, "B");
// = "2.04KiB"
打印精确的千克,百万值(这里用W =瓦特):
UnitFormatter.formatAsUnits(12_000_678, UnitSystem.SI, "W", ", ");
// = "12MW, 678W"
你可以传递一个DecimalFormat来定制输出:
UnitFormatter.formatAsUnit(2085, UnitSystem.IEC, "B", new DecimalFormat("0.0000"));
// = "2.0361KiB"
对于kilo或mega值的任意操作,您可以将它们拆分为组件:
UnitComponent uc = new UnitComponent(123_345_567_789L, UnitSystem.SI);
int kilos = uc.kilo(); // 567
int gigas = uc.giga(); // 123
这是另一个简洁的解决方案,没有循环,但具有区域敏感格式和正确的二进制前缀:
import java.util.Locale;
public final class Bytes {
private Bytes() {
}
public static String format(long value, Locale locale) {
if (value < 1024) {
return value + " B";
}
int z = (63 - Long.numberOfLeadingZeros(value)) / 10;
return String.format(locale, "%.1f %siB", (double) value / (1L << (z * 10)), " KMGTPE".charAt(z));
}
}
测试:
Locale locale = Locale.getDefault()
System.out.println(Bytes.format(1L, locale))
System.out.println(Bytes.format(2L * 1024, locale))
System.out.println(Bytes.format(3L * 1024 * 1024, locale))
System.out.println(Bytes.format(4L * 1024 * 1024 * 1024, locale))
System.out.println(Bytes.format(5L * 1024 * 1024 * 1024 * 1024, locale))
System.out.println(Bytes.format(6L * 1024 * 1024 * 1024 * 1024 * 1024, locale))
System.out.println(Bytes.format(Long.MAX_VALUE, locale))
输出:
1 B
2.0 KiB
3.0 MiB
4.0 GiB
5.0 GiB
6.0 PiB
8.0 EiB
使用下面的函数来获得确切的信息。它是基于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(长持续时间)。