2025-08-24 21:42:47 +08:00
|
|
|
package com.mini.capi.utils;
|
|
|
|
|
|
2025-08-24 22:56:43 +08:00
|
|
|
import java.math.BigDecimal;
|
|
|
|
|
import java.math.RoundingMode;
|
2025-08-24 21:42:47 +08:00
|
|
|
|
2025-08-24 22:56:43 +08:00
|
|
|
public class vF {
|
2025-08-24 21:42:47 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
private static final String[] UNITS = {"B", "K", "M", "G", "T", "P"};
|
2025-08-24 22:56:43 +08:00
|
|
|
private static final BigDecimal KB = BigDecimal.valueOf(1024L);
|
2025-08-24 21:42:47 +08:00
|
|
|
|
|
|
|
|
public static String format(long bytes) {
|
|
|
|
|
if (bytes < 0) {
|
|
|
|
|
throw new IllegalArgumentException("字节数不能为负数");
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-24 22:56:43 +08:00
|
|
|
BigDecimal size = BigDecimal.valueOf(bytes);
|
2025-08-24 21:42:47 +08:00
|
|
|
int unitIndex = 0;
|
|
|
|
|
|
2025-08-24 22:56:43 +08:00
|
|
|
while (size.compareTo(KB) >= 0 && unitIndex < UNITS.length - 1) {
|
|
|
|
|
size = size.divide(KB, 2, RoundingMode.HALF_UP);
|
2025-08-24 21:42:47 +08:00
|
|
|
unitIndex++;
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-24 22:56:43 +08:00
|
|
|
String num = size.stripTrailingZeros().toPlainString();
|
|
|
|
|
return num + UNITS[unitIndex];
|
2025-08-24 21:42:47 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|